Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EXC_BAD_ACCESS using ARC only during testing

I have an issue where I'm getting bad access exceptions but only when running a testing build (calling the same methods in a debug build doesn't cause the problem to come up). The project has ARC enabled and I'm running this on the iPad 5.1 simulator using Xcode 4.3:

Here's where the problem crops up:

- (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);
}

At the point when the addObserver: method is called it doesn't seem like any of the objects involved should have been released so what could be causing the exception?

EDIT:

Apologies if it wasn't clear but the code above is being executed as part of a test case (using the standard Xcode OCUnit). Also in case it clarifies anything here's the relevant code from the player class (there's other ivars and methods but they don't have any connection to the property or methods being tested):

// 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"];    
}
like image 987
Mattia Avatar asked Apr 20 '12 13:04

Mattia


1 Answers

If your class is indeed key-value compliant, ensure that the implementation for the class exhibiting the issue is not included in your test product. This means that the Target Membership panel of the Identity inspector for your .m file should only have your app checked (not YourAppTests).

I experienced the same issue in Xcode 4.3.1 when an implementation was included in both products and I registered observers in both production and test code. The following logs tipped me off:

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.

like image 178
Mark Schabacker Avatar answered Sep 27 '22 22:09

Mark Schabacker