首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在@throw之后保留耗尽的计数

在@throw之后保留耗尽的计数
EN

Stack Overflow用户
提问于 2012-03-06 12:23:22
回答 3查看 856关注 0票数 0

当我在SenTest的STAssertThrowsSpecificNamed发出的调用中运行此代码时

代码语言:javascript
复制
@throw [[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                  reason:@"---some reason----"
                               userInfo:nil];

我得到(使用NSZombieEnabled=YES):

代码语言:javascript
复制
*** -[NSException reason]: message sent to deallocated instance 0x100a81d60

STAssertThrowsSpecificNamed完成对异常的处理之前,异常以某种方式被释放。

我可以通过用下面的代码替换上面的@throw行来避免这个错误:

代码语言:javascript
复制
NSException *exception = [NSException exceptionWithName:NSInvalidArchiveOperationException
                                                 reason:@"---some reason----"
                                               userInfo:nil];
@throw exception;

不管有没有ARC,我都会得到完全相同的行为。如果没有ARC,此代码也可以避免错误:

代码语言:javascript
复制
@throw [[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                   reason:@"---some reason----"
                                userInfo:nil] retain];

这是SenTest中的错误吗?或者编译器中的bug?或者是我的第一个@throw不正确?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-05-18 12:21:56

我现在只在ARC和手动保留-释放模式下使用+[NSException raise:format:]

票数 1
EN

Stack Overflow用户

发布于 2012-03-06 12:40:03

@throw在使用完对象后释放它,所以如果你想把它包含在与@throw相同的行上,请使用-retain。

代码语言:javascript
复制
@throw [[[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                  reason:@"---some reason----"
                               userInfo:nil] retain] autorelease];

这应该能起到作用。

编辑:要检查特定于ARC的代码,请使用:

代码语言:javascript
复制
if(__has_feature(objc_arc)) {
    @throw [[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                       reason:@"---some reason----"
                                     userInfo:nil];
} else {
    @throw [[[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                      reason:@"---some reason----"
                                   userInfo:nil] retain] autorelease];
}
票数 2
EN

Stack Overflow用户

发布于 2012-03-09 03:11:35

我坚持这个形式,目前,这似乎是工作,无论有没有弧的

代码语言:javascript
复制
id exc = [NSException exceptionWithName:NSInvalidArchiveOperationException
                                 reason:@"---some reason----"
                               userInfo:nil];
@throw exc;

根据Galaxas0的回答,@throw被设计为在处理异常之后释放它。这仍然让我感到奇怪,特别是在ARC下。

在非ARC项目中,使用以下代码(也适用于Galaxas0):

代码语言:javascript
复制
@throw [[[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                    reason:@"---some reason----"
                                  userInfo:nil] retain] autorelease];
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9577860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档