虽然标题是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提供修改的机会。