【发布时间】:2012-11-08 11:52:30
【问题描述】:
有谁知道如何在第一次异步通信的完成块中启动另一个新的异步方法的最佳实践?
我正在测试代码以在另一个与 Facebook 的异步通信的完成回调中异步调用 NSFetchRequest(coz 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
我试过了:
How do I wait for an asynchronously dispatched block to finish?
NSURLConnection sendAsynchronousRequest:queue:completionHandler: making multiple requests in a row?
:
- (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");
}];
}
【问题讨论】:
-
您是否尝试过在 alloc/init 之后使用 retain 调用 fetcheRequest,然后在使用它调用 release 之后调用?
-
谢谢 yulz,我试过了,但对我不起作用。
-
首先,你不需要复制和自动释放块。 “问题可能是它在 NSFetchRequest 完成之前从内存中释放调用者块” 什么?这种说法没有任何意义
标签: objective-c asynchronous objective-c-blocks nsfetchrequest stackmob