gpt4 book ai didi

objective-c - @catch block 中捕获的对象的生命周期是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 19:44:50 25 4
gpt4 key购买 nike

当您在 ObjC @catch block 中捕获异常时,该异常对象的生命周期是多少?我知道我可以在 block 内安全地使用它,但是如果我想在 block 之后再次使用它怎么办,就像这样?

NSException * exception = nil;
@try {
// do something risky
} @catch(NSException * e) {
exception = e;
}

if (exception) {
NSLog(@"Caught exception: %@", exception);
}

我可以安全地将引用存储到另一个本地吗?为了安全起见,我应该保留,自动释放吗?我可以保留它并无限期地持有它吗?

(如果我分配给本地,或者保留并在以后使用,它似乎工作正常,但文档并没有真正讨论这个对象在所有权方面“来自”哪里,或者它是否特殊,所以我正在寻找更清晰的信息。)

最佳答案

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Exceptions/Tasks/HandlingExceptions.html

Almost all NSException objects (and other types of exception objects) are created autoreleased, which assigns them to the nearest (in scope) autorelease pool. When that pool is released, the exception is destroyed.

此外,我很确定 memory programming guide 中的某处,他们提到名称中没有 newalloccopy 的方法总是按照约定返回自动释放的对象。 NSException's methods符合条件。

稍微相关(不是 NSException 而是 NSError):

If you create an NSError object with initWithDomain:code:userInfo:, you should send autorelease to it before you return it to the caller.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html

关于objective-c - @catch block 中捕获的对象的生命周期是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8364834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com