有人知道如何在第一个异步通信的完成块中启动另一个新的异步方法的最佳实践吗?
我正在测试代码,以在Facebook的另一个异步通信的完成回调中异步调用NSFetchRequest(因为STACKMOB iOS SDK在内部与服务器同步)。代码执行在NSFetchRequest的行突然终止。我意识到它不能正确工作的原因之一。
我猜想完成块一旦调用[managedObjectContext executeFetchRequest:fetchRequest error:&error],就已经从内存中释放了。
但我不知道更好的解决方案来解决这个问题。感谢任何帮助。
SDK使用:
- (void)queueRequest:(NSURLRequest *)request options:(SMRequestOptions *)options 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");
}];
}