0

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

@throw [[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                  reason:@"---some reason----"
                               userInfo:nil];

我得到(带NSZombieEnabled=YES):

*** -[NSException reason]: message sent to deallocated instance 0x100a81d60

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

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

NSException *exception = [NSException exceptionWithName:NSInvalidArchiveOperationException
                                                 reason:@"---some reason----"
                                               userInfo:nil];
@throw exception;

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

@throw [[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                   reason:@"---some reason----"
                                userInfo:nil] retain];

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

4

3 回答 3

2

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

@throw [[[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                  reason:@"---some reason----"
                               userInfo:nil] retain] autorelease];

这应该可以解决问题。

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

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];
}
于 2012-03-06T04:40:03.040 回答
1

我现在坚持使用这种形式,无论有没有 ARC ,它似乎都有效。

id exc = [NSException exceptionWithName:NSInvalidArchiveOperationException
                                 reason:@"---some reason----"
                               userInfo:nil];
@throw exc;

根据 Galaxas0 的回答,@throw旨在在处理异常后释放异常。这仍然让我觉得很奇怪,尤其是在 ARC 下。

在非 ARC 项目中,使用它(也按 Galaxas0):

@throw [[[[NSException alloc] initWithName:NSInvalidArchiveOperationException
                                    reason:@"---some reason----"
                                  userInfo:nil] retain] autorelease];
于 2012-03-08T19:11:35.063 回答
1

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

于 2013-05-18T04:21:56.273 回答