@catch块中捕获的对象的生命周期是什么? [英] What is the lifecycle of an object caught in a @catch block?

查看:183
本文介绍了@catch块中捕获的对象的生命周期是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您在ObjC @catch块中捕获异常时,该异常对象的生命周期是什么?我知道我可以安全地在块内使用它,但是如果我想在块之后再次使用它呢?

When you catch an exception in an ObjC @catch block, what is the lifecycle of that exception object? I know I can safely use it inside the block, but what if I want to use it again after the block, like this?

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

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

我可以安全地将引用保存到另一个本地吗?为了安全起见,我应该retain, autorelease吗?我可以保留它并无限期坚持吗?

Can I safely stash the reference into another local? Should I be retain, autoreleaseing it for safety? Can I retain it and hold onto it indefinitely?

(如果我分配给本地对象,或者以后保留并使用,这似乎工作正常,但是文档并没有真正讨论该对象的来源"所有权,或者它是否特殊,所以我正在寻求更多的清晰度.)

(It does seem to work OK if I assign to the local, or retain and use later, but the docs don't really discuss where this object "comes from" in terms of ownership, or if it's special, so I was looking for more clarity.)

推荐答案

几乎所有NSException对象(以及其他类型的异常对象)都是自动释放的,这会将它们分配给最近的(在范围内)自动释放池.释放该池后,该异常将被销毁.

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.

此外,我非常确定 NSException的方法有资格.

Also, I'm pretty sure that somewhere in the memory programming guide, they mention that methods without new or alloc or copy in their names always return autoreleased objects by convention. NSException's methods qualify for that.

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

Slightly related (not NSException but NSError):

如果您使用initWithDomain:code:userInfo:创建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

这篇关于@catch块中捕获的对象的生命周期是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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