NSError

虽然标题是NSError,但是我们不打算讲NSError怎么用的,因为它是一个很纯粹的模型类,无需赘述其用法。

问题的关键是,我们要考虑一些场合:

参考http://amattn.com/2011/12/

NSError

The ubiquitous NSError is a little bit tricky. Typical Cocoa convention is that they are implemented 
via out-parameters (aka indirect pointers).

In ARC, out-parameters are by default __autoreleasing and should be implemented like this:

- (BOOL)performWithError:(__autoreleasing NSError **)error
{
    // ... some error occurs ...
    if (error)
    {
        // write to the out-parameter, ARC will autorelease it
        *error = [[NSError alloc] initWithDomain:@"" 
                                            code:-1 
                                        userInfo:nil];
        return NO;
    }
    else
    {
        return YES;
    }
}

When using an out-parameter, you will usually use __autoreleasing on your *error object like so:

NSError __autoreleasing *error = error;
BOOL OK = [myObject performOperationWithError:&error];
if (!OK)
{
    // handle the error.
}

If you forget the __autoreleasing, the compiler will simply insert a temporary, 
intermediate autoreleasing object for you. 
This was a compromise made under the oppressive regime of backwards compatibility. 
I have seen some compiler configurations which do not automatically make them __autoreleasing. 
It is safer to include the __autoreleasing for all new code.

一般NSError用作out参数,在方法内部产生。在ARC中,它的释放时机应该是自动释放的。在外部,为确保类型一致,应该使用一个自动释放的指针来接收。

__autoreleasing NSString *retStr和 NSString * __autoreleasing retStr都是正确的写法。现在变成二维指针时,需要把*retStr看成一个整体,代表reStr的上一级指针,所以就变成了NSString * __autoreleasing *retStr。



http://stackoverflow.com/questions/11678528/ios-autoreleasing-const-error 中提到的问题和block有关系,用于接收的指针在block之外声明,在内部是const的,需要加上__block提供修改的机会。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值