使用ARC在块内设置NSError [英] Setting NSError within a block, using ARC

查看:111
本文介绍了使用ARC在块内设置NSError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望使用以下命令从项目的块内设置NSError指针 自动参考计数.接下来是我的代码的简化版本:

I wish to set an NSError pointer from within a block in a project using automatic reference counting. What follows is a simplified version of my code:

- (BOOL)frobnicateReturningError:(NSError **)error
{
    NSArray *items = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];

    __block Frobnicator *blockSelf = self;
    [items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
        [blockSelf doSomethingWithItem:item error:error];
    }];
}

这可以编译,但是给定的error可以通过以下方式修改 doSomethingWithItem我尝试为该块创建本地NSError 修改,然后将其用于在设置之后的原始error 枚举(我没有显示):

This compiles but given error may be modified by doSomethingWithItem I tried creating a local NSError for the block to modify, which would then be used to set the original error after the enumeration (which I haven't shown):

- (BOOL)frobnicateReturningError:(NSError **)error
{
    NSArray *items = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];

    __block Frobnicator *blockSelf = self;
    __block NSError *blockError = nil;
    [items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
        [blockSelf doSomethingWithItem:item error:&blockError];
    }];
}

这无法编译并出现以下错误:

This fails to compile with the following error:

将非本地对象的地址传递给__autoreleasing参数进行写回

passing address of non-local object to __autoreleasing parameter for write-back

搜索该错误仅返回Clang源代码本身的结果.

Googling for this error only returns results from the Clang source code itself.

一种似乎可行但有点丑陋的解决方案是具有内部和外部错误指针:

One solution that seems to work but is a bit ugly is to have an inner and outer error pointer:

- (BOOL)frobnicateReturningError:(NSError **)error
{
    NSArray *items = [NSArray arrayWithObjects:@"One", @"Two", @"Three", nil];

    __block Frobnicator *blockSelf = self;
    __block NSError *outerError = nil;
    [items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
        NSError *innerError = nil;
        [blockSelf doSomethingWithItem:item error:&innerError];
        outerError = innerError;
    }];
}

从块内设置NSError的正确方法是什么?

What is the correct way to set an NSError from within a block?

推荐答案

尝试一下:

// ...
__block NSError *blockError = nil;
[items enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
    NSError *localError = nil;
    if (![blockSelf doSomethingWithItem:item error:&localError]) {
        blockError = localError;
    }
}];
// ...

至于为什么这是必要的,我仍在尝试自己掌握这一点.当我这样做时,我将更新此答案. :)

As for exactly why this is necessary, I'm still trying to get a grasp on that myself. I'll update this answer when I do. :)

这篇关于使用ARC在块内设置NSError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆