当我在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中的错误吗?或者编译器中的bug?或者是我的第一个@throw不正确?
发布于 2013-05-18 12:21:56
我现在只在ARC和手动保留-释放模式下使用+[NSException raise:format:]。
发布于 2012-03-06 12:40:03
@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-09 03:11:35
我坚持这个形式,目前,这似乎是工作,无论有没有弧的。
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];https://stackoverflow.com/questions/9577860
复制相似问题