我正在尝试处理 completionBlock
错误并在出现任何异常时捕获它。
以下是我的代码:
ParseOperation *parser = [[ParseOperation alloc] initWithData:self.appListData];
if([[ParseOperation alloc] initWithData:self.appListData] == nil)
NSLog(@"[[ParseOperation alloc] initWithData:self.appListData] is nill");
__weak ParseOperation *weakParser = parser;
parser.completionBlock = ^(void) {
if (weakParser.appRecordList) {
dispatch_async(dispatch_get_main_queue(), ^{
RootViewController *rootViewController = (RootViewController*)[(UINavigationController*)self.window.rootViewController topViewController];
rootViewController.entries = weakParser.appRecordList;
if(weakParser.appRecordList == nil)
NSLog(@"weakParser.appRecordList is nill");
if(weakParser.appRecordList != nil)
NSLog(@"weakParser.appRecordList is Not nill");
[rootViewController.tableView reloadData];
});
}
self.queue = nil;
};
我在我的类中实现了以下内容以在控制台上获取错误结果:
parser.errorHandler = ^(NSError *parseError) {
dispatch_async(dispatch_get_main_queue(), ^{
[self handleError:parseError];
NSLog(@"[self handleError:parseError] %@", parseError);
});
};
weakParser.appRecordList
大部分时间返回 nil
(错误情况)。
ParseOperation
类中有问题吗?
最佳答案
问题是,你需要在weakParser之前添加__block,否则,当completion block运行时,将没有对weakParser的引用。 请注意,变量在声明时被分配给 block ,如果它们没有设置为 __block,它们的值将被传递给 block (而不是指针 a.k.a. 引用)并且因为在您的情况下,它是一个弱引用,当它到达方法的底部时,它将被释放并且 block 永远没有机会对其采取行动。 希望这会有所帮助:Apple Programming Guide: Working with blocks
[编辑] P.S.:我不确定,但我认为从 weakParser 中删除 __weak 也可以解决问题。
关于ios - completionBlock错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22006541/