Reputation: 357
I have this property in my .h file:
@property (nonatomic, readwrite) NSInteger gameMode;
And I have this setter in the corresponding .m file:
- (void)setGameMode:(NSInteger)mode {
self.gameMode = mode;
NSLog(@"game mode %d", self.gameMode);
}
In my view controller, I have this function to call the setter when I touch a button:
- (IBAction)touchCardButton:(UIButton *)sender {
if ([self.game disableModeChooseAtFirstTouch]) {
[self.game setGameMode:self.modeSegmentedControl.selectedSegmentIndex];
}
But when I click the button in simulator, it will stop here:
self.gameMode = mode;
And says:
Thread 1: EXC_BAD_ACCESS
Update: If I add a NSLog before it, like this:
- (void)setGameMode:(NSInteger)mode {
NSLog(@"game mode %d", self.gameMode);
self.gameMode = mode;
NSLog(@"game mode %d", self.gameMode);
}
It will keep printing game mode: 0
Can anybody tell me why? Thanks!
Upvotes: 0
Views: 61
Reputation: 131408
Yes, I can tell you why. You are invoking the setter in the setter, causing infinite recursion, stack overflow, and a crash.
Your setGameMode method should read:
- (void)setGameMode:(NSInteger)mode
{
_gameMode = mode; //Don't use the setter in the implementation of the setter.
NSLog(@"game mode %d", self.gameMode);
}
Upvotes: 3