はい、もちろん、getAPI
呼び出しparseAPI
の場合、コードparseAPI
は実行されたスレッドと同じスレッドでgetAPI
実行されるため、この例ではバックグラウンド キューで実行されます。
completionBlock
最後にコールバックをメイン スレッドに戻すには、複数の Apple API で見られるようにApple が使用するのと同じテクニックを使用しdispatch_block_t
ますvoid(^)(NSError*)
。getAPI:
に渡すparseAPI:
と、次にそれが渡さsavetoDB:
れ、最後に、メインスレッドでこのコードブロック (メソッドからメソッドに渡される) を呼び出すためにsavetoDB:
使用できます。dipatch_async(dispatch_get_main_queue, completionBlock);
注: getAPI の場合、Apple のsendAsynchronousRequest:queue:completionHandler:
メソッドを使用できます。これにより、バックグラウンドでリクエストが自動的に実行され、指定された完了ブロックが呼び出されますNSOperationQueue
( NSOperationQueue
GCD の dispatch_queue を内部で使用します)。詳細についてはNSOperationQueue
、GCD およびConcurrency Programming Guideのドキュメントと、Apple doc のすべての詳細なガイドを参照してください。
-(void)getAPI:( void(^)(NSError*) )completionBlock
{
NSURLRequest* req = ...
NSOperationQueue* queue = [[NSOperationQueue alloc] init]; // the completionHandler will execute on this background queue once the network request is done
[NSURLConnection sendAsynchronousRequest:req queue:queue completionHandler:^(NSURLResponse* resp, NSData* data, NSError* error)
{
if (error) {
// Error occurred, call completionBlock with error on main thread
dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(error); });
} else {
[... parseAPI:data completion:completionBlock];
}
}];
}
-(void)parseAPI:(NSData*)dataToParse completion:( void(^)(NSError*) )completionBlock
{
... parse datatToParse ...
if (parsingError) {
dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(error); });
} else {
[... savetoDB:dataToSave completion:completionBlock];
}
}
-(void)savetoDB:(id)dataToSave completion:( void(^)(NSError*) )completionBlock
{
... save to your DB ...
// Then call the completionBlock on main queue / main thread
dispatch_async(dispatch_get_main_queue(), ^{ completionBlock(dbError); }); // dbError may be nil if no error occurred of course, that will tell you everything worked fine
}
-(void)test
{
[... getAPI:^(NSError* err)
{
// this code will be called on the main queue (main thread)
// err will be nil if everythg went OK and vontain the error otherwise
}];
}