EXC_BAD_ACCESS using ARC only during testing

I have a problem when I get invalid exceptions, but only when the test assembly is complete (calling the same methods in the debug assembly does not cause a problem). ARC is included in the project, and I run it on the iPad 5.1 simulator using Xcode 4.3:

This is where the problem arises:

- (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 time the addObserver: method is addObserver: , does not it appear that any of the objects involved were to be released, so what could throw an exception?

EDIT:

Sorry if this wasn’t clear, but the above code runs as part of a test case (using the standard Xcode OCUnit). Also, if he clarifies something here, the corresponding code from the player's class (there are other ivars and methods, but they have nothing to do with 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"]; } 
+7
source share
2 answers

If your class is indeed compatible with key values, make sure that the implementation for the class exhibiting the problem is not included in your test product. This means that in the target panel of the identity inspector for your .m file, only your application (and not YourAppTests) should be checked.

I encountered the same problem in Xcode 4.3.1 when an implementation was included in both products, and I registered observers in both production and test codes. The following magazines knocked me over:

YourClass class is implemented as in / 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.

+21
source

According to the Key Values ​​Monitoring Programming Guide , does your player match the key value? You want to make sure that you are KVC Compliant . I also assume that you also implemented your observeValueForKeyPath:ofObject:change:context: :? If you think you have done all this and are still not working, perhaps you can share your code.

It’s also a minor thing, but I guess this is a piece of code to highlight the problem. I only mention this because ARC is about to release your p-object at the end of your testChangeFoodNotification, and I would think that you want to remove your observer first.

0
source

All Articles