有谁知道如何在第一个异步通信的完成块中启动另一个新的异步方法的最佳实践?
我正在测试代码以在另一个与 Facebook 的异步通信的完成回调中异步调用 NSFetchRequest(coz STACKMOB iOS SDK 在内部与服务器同步)。代码的执行突然在 NSFetchRequest 行终止。我意识到它无法正常工作的原因之一。我猜想一旦 [managedObjectContext executeFetchRequest:fetchRequest error:&error] 被调用,完成块就已经从内存中释放了。但我不知道更好的解决方案来解决它。谢谢你的帮助。
SDK 使用:
- (void)queueRequest:(NSURLRequest *)请求选项:(SMRequestOptions *)选项 onSuccess:(SMFullResponseSuccessBlock)onSuccess onFailure:(SMFullResponseFailureBlock)onFailure
https://github.com/stackmob/stackmob-ios-sdk/blob/master/Classes/SMDataStore%2BProtected.m
我试过了:
:
- (IBAction)checkFacebookInfo:(id)sender
{
//completion block of facebook info
void(^onCompleteBlock)(NSDictionary*) = [[^(NSDictionary* userInfo)
{
NSManagedObjectContext *managedObjectContext = nil;
managedObjectContext = [[SingletonCoreData sharedManager] managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"User"];
//for STACKMOB, customized NSFetchRequest internally sync to the server. It is Asynchronous method.
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];// failed
//Not reached here
//set userInfo to results here
} copy] autorelease];
//invoke onCompleteBlock after executing asynchronously, client(SMClient object for STACKMOB)
[client getLoggedInUserFacebookInfoWithOnSuccess:onCompleteBlock onFailure:^(NSError *error)
{
NSLog(@"No user found");
}];
}
编辑: 我试过这个写在下面,然后它成功地工作了。但是我觉得慢。我将部分代码放入“dispatch_async”块中。我正在等待任何其他更好的解决方案。
- (IBAction)checkFacebookInfo:(id)sender
{
//completion block of facebook info
void(^onCompleteBlock)(NSDictionary*) = ^(NSDictionary* userInfo)
{
dispatch_queue_t gQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(gQueue, ^{
NSManagedObjectContext *managedObjectContext = nil;
managedObjectContext = [[SingletonCoreData sharedManager] managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"User"];
//for STACKMOB, customized NSFetchRequest internally sync to the server. It is Asynchronous method.
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];// success
//set userInfo to results here
});
};
//invoke onCompleteBlock after executing asynchronously, client(SMClient object for STACKMOB)
[client getLoggedInUserFacebookInfoWithOnSuccess:onCompleteBlock onFailure:^(NSError *error)
{
NSLog(@"No user found");
}];
}