completionBlock错误处理

时间:2014-02-25 06:40:49

标签: ios parsing error-handling

我正在尝试处理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类吗?

2 个答案:

答案 0 :(得分:2)

问题是,您需要在weakParser之前添加 __ block ,否则,当完成块运行时,将不会引用 weakParser 。 请注意,变量在声明时分配给块,如果它们未设置为 __ block ,则它们的值将传递给块(而不是指针也称为引用),因为在你的情况下它是一个弱引用,当它到达方法的底部时,它将被释放并且块永远不会有机会对它采取行动。 希望这会有所帮助:Apple Programming Guide: Working with blocks

[编辑] P.S。:我不确定,但我认为从weakParser中删除 __弱也可以解决问题。

答案 1 :(得分:1)

我认为这是关于__weak在块中的使用,下面的代码帮助调度方法传递appRecordList值:

id appRecordList = weakParser.appRecordList;
if (appRecordList) {
        dispatch_async(dispatch_get_main_queue(), ^{
            RootViewController *rootViewController = (RootViewController*)[(UINavigationController*)self.window.rootViewController topViewController];
            rootViewController.entries = appRecordList;
            if(appRecordList== nil)
                 NSLog(@"weakParser.appRecordList is nill");
            if(appRecordList != nil)
                NSLog(@"weakParser.appRecordList is Not nill");
            [rootViewController.tableView reloadData];
        });
    }