ios - xcode objective-c ,EXC_BAD_ACCESS

标签 ios objective-c xcode

我的 .h 文件中有这个属性:

@property (nonatomic, readwrite) NSInteger gameMode;

我在相应的 .m 文件中有这个 setter:

- (void)setGameMode:(NSInteger)mode {
    self.gameMode = mode;
    NSLog(@"game mode %d", self.gameMode);
}

在我的 View Controller 中,我有这个函数可以在我触摸按钮时调用 setter :

- (IBAction)touchCardButton:(UIButton *)sender {
    if ([self.game disableModeChooseAtFirstTouch]) {
        [self.game setGameMode:self.modeSegmentedControl.selectedSegmentIndex];
}

但是当我在模拟器中点击按钮时,它会停在这里:

self.gameMode = mode;

并说:

Thread 1: EXC_BAD_ACCESS

更新: 如果我在它之前添加一个 NSLog,像这样:

- (void)setGameMode:(NSInteger)mode {
    NSLog(@"game mode %d", self.gameMode);
    self.gameMode = mode;
    NSLog(@"game mode %d", self.gameMode);
}

它将继续打印game mode: 0

stack trace stack trace

谁能告诉我为什么?谢谢!

最佳答案

是的,我可以告诉你原因。你在 setter 中调用 setter,导致无限递归、堆栈溢出和崩溃。

您的 setGameMode 方法应为:

- (void)setGameMode:(NSInteger)mode 
{
    _gameMode = mode;  //Don't use the setter in the implementation of the setter.
    NSLog(@"game mode %d", self.gameMode);
}

关于ios - xcode objective-c ,EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24347526/

相关文章:

ios - 如何在旋转时重绘 View 布局?

objective-c - 如何在枚举期间删除 NSMutableArray 或 NSMutableDictionary 中的元素?

iphone - iOS本地通知: I would like to execute a function upon reentering the app via local notification

ios - 更改 map 图钉(颜色或图像)

ios - 在 Xcode 4.x 中编译大型源文件(10k+ 行)

ios 像 mspy 一样读取短信和通话记录

ios - 从右向左滑动手指,反之亦然 :-)

ios - UIView 只会动画一次

XCode 6 测试文件夹

ios - Xcode 停止在设备上工作