好吧,我不会假装对 Objective-C 和 iOS 编程了如指掌,因为我才刚刚开始,但这个让我完全不知所措。我有一个类,ShoppingListViewController,在那个类中,我覆盖了 initWithCoder 方法来读取:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
self.title = @"Shopping List";
[self loadItems];
}
return self;
}
在那个 loadItems 方法中,有一行导致应用程序每次打开时崩溃:
self.items = [NSMutableArray array];
应用程序崩溃并出现以下错误:
Terminating app due to uncaught exception 'NSInternalInconsistencyException',
reason: 'Could not load NIB in bundle:
但是,如果我用以下内容替换该行:
_items = [NSMutableArray array];
一切正常。现在我知道我通过这样做来规避默认 setter ,但我不清楚为什么运行时通常会出现问题,以及为什么它与 NIB 文件有关?谁能赐教一下?
更新更多信息:
items 属性在类的 header 中声明:
@property (nonatomic) NSArray *items;
而且 loadItems 方法非常稀疏,基本上只有那一行在第一次加载时真正重要:
- (void)loadItems {
NSString *filePath = [self pathForItems];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
self.items = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
} else {
_items = [NSMutableArray array];
}
}
最佳答案
您不应该在 init 或 dealloc 中向 self 发送消息。阅读this article为了更好的解释
This is because self.whatever will trigger other side effects, such as Key-Value Observing (KVO) notifications, or maybe your class implements (explicitly) or a subclass overrides setWhatever: -- and that could expose your partially initialized instance to other APIs (including its own), which rightly assume they are dealing with a fully constructed object.
可以引用this answer了解更多信息。
附言永远不要忘记 self.something 会调用 setter/getter。
关于ios - 使用 self 时奇怪的 iOS 应用程序崩溃行为。通过实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322390/