संभव डुप्लिकेट:
Grand Central Dispatch (GCD) vs. performSelector - need a better explanationdispatch_async का उपयोग करके मुख्य थ्रेड पर यूआई परिवर्तन करें या प्रदर्शन चयन करेंऑनमेन थ्रेड?
मुख्य थ्रेड पर "सामान" पर अमल करने के लिए, मैं dispatch_async
या performSelectorOnMainThread
इस्तेमाल करना चाहिए? क्या कोई पसंदीदा तरीका है, सही/या गलत, और/या सर्वोत्तम अभ्यास?
उदाहरण: मैं NSURLConnection sendAsynchronousRequest:urlRequest
विधि के ब्लॉक के भीतर कुछ तर्क कर रहा हूं। क्योंकि मैं मुख्य दृश्य में सामान कर रहा हूं जैसे UIAlertView
प्रस्तुत करने के लिए मुझे मुख्य धागे पर UIAlertView
दिखाना होगा। ऐसा करने के लिए मैं निम्नलिखित कोड का उपयोग कर रहा हूँ।
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// code snipped out to keep this question short
if(![NSThread isMainThread])
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
});
}
}];
उसी if(![NSThread isMainThread])
कथन के भीतर मैं कुछ कस्टम तरीकों को भी कॉल करता हूं। सवाल यह है कि, क्या मुझे ऊपर उपयोग कर रहे dispatch_async
विधि का उपयोग करना चाहिए या इसके बजाय performSelectorOnMainThread
का उपयोग करना बेहतर है? उदाहरण के लिए, नीचे पूर्ण कोड:
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// code snipped out to keep this question short
if(![NSThread isMainThread])
{
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"Some Message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView show];
// call custom methods in dispatch_async?
[self hideLoginSpinner];
});
// or call them here using performSelectorOnMainThread???
[self performSelectorOnMainThread:@selector(hideLoginSpinner) withObject:nil waitUntilDone:NO];
}
}];
FYI करें - अगर मैं करते वह मुख्य थ्रेड पर इन कार्यवाहियों को नहीं मैं कुछ सेकंड की देरी जब UIAlertView
पेश देख सकते हैं और मैं डिबगर wait_fences: failed to receive reply: 10004003
में निम्न संदेश प्राप्त होता है। मैंने सीखा है कि ऐसा इसलिए है क्योंकि आपको मुख्य धागे पर UI में परिवर्तन करने की आवश्यकता है ... यदि कोई सोच रहा है कि मैं ऐसा क्यों कर रहा हूं जो मैं कर रहा हूं ...
निकट से संबंधित: [क्या performSelectorOnMainThread बीच क्या अंतर है? मुख्य कतार पर और dispatch_async()] (http://stackoverflow.com/questions/9335434/) –
_writing_ कोड की पीओवी से सबसे स्पष्ट अंतर यह है कि एक ब्लॉक प्रेषण अधिक लचीला है: उदाहरण के लिए, आदिम तर्कों को संभालना आसान तरीका है। –