我有一个问题,我遇到了错误的访问异常,但只有在运行测试构建时才会出现(在调试构建中调用相同的方法不会导致问题出现)。该项目启用了 ARC,我正在使用 Xcode 4.3 在 iPad 5.1 模拟器上运行它:
这里是问题出现的地方:
- (void)testChangeFoodNotification {
Player* p = [[Player alloc] init];
[p addObserver:self forKeyPath:@"food" options:0 context:0]; // <-EXC_BAD_ACCESS (code=2)
p.food += 1;
STAssertTrue(_wasNotifiedOfFoodChange, nil);
}
在调用 addObserver:
方法时,似乎不应该释放所涉及的任何对象,那么可能导致异常的原因是什么?
编辑:
抱歉,如果不清楚,但上面的代码是作为测试用例的一部分执行的(使用标准 Xcode OCUnit)。此外,如果它澄清了这里的任何内容,请使用播放器类的相关代码(还有其他 ivar 和方法,但它们与正在测试的属性或方法没有任何联系):
// Public interface
@interface Player : NSObject
@property (nonatomic, assign) NSInteger food;
@end
// Private interface
@interface Player() {
NSInteger _food;
}
@end
@implementation Player
@synthesize food = _food;
#pragma mark - Getters/Setters
- (void)setFood:(NSInteger)food {
[self willChangeValueForKey:@"food"];
_food = food;
[self didChangeValueForKey:@"food"];
}
最佳答案
如果您的类确实符合键值对,请确保您的测试产品中不包含出现问题的类的实现。这意味着您的 .m 文件的身份检查器的目标成员资格面板应该只检查您的应用程序(而不是 YourAppTests)。
我在 Xcode 4.3.1 中遇到了同样的问题,当时两种产品都包含一个实现,并且我在生产和测试代码中都注册了观察者。以下日志提示了我:
Class YourClass is implemented in both /Users/yourUser/Library/Application Support/iPhone Simulator/5.1/Applications//YourApp.app/YourApp and /Users/yourUser/Library/Developer/Xcode/DerivedData/YourApp-/Build/Products/Debug-iphonesimulator/YourAppTests.octest/YourAppTests. One of the two will be used. Which one is undefined.
关于ios - EXC_BAD_ACCESS 仅在测试期间使用 ARC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10246783/