ios - 使用 self 时奇怪的 iOS 应用程序崩溃行为。通过实例变量

标签 ios objective-c

好吧,我不会假装对 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/

相关文章:

iphone - 手动 segue 时导航栏不可见

ios - 如何检测 IOS 7 和 IOS 8 以及宽屏 iPhone 尺寸以使我的应用通用?

objective-c - 区分对同一委托(delegate)方法的调用

javascript - UIWebView JavaScript 丢失对 iOS JSContext 命名空间(对象)的引用

ios - 自定义单元格按钮单击

ios - Setter 中的静态变量

iphone - NSString 中有setwidth 吗?

ios - 如何在同一相册的 Facebook 和 Twitter 上使用 SLComposeViewController 发布多张图片

ios - 为什么我无法使用 [transitionContext viewControllerForKey :UITransitionContextFromViewKey] 获取 FromVC 和 ToVC

ios - swift 核心数据 : error: Failed to call designated initializer on NSManagedObject class 'NSManagedObject'