【问题标题】:Why would an auto-synthesized property's ivar remain nil even after the property is set?为什么即使设置了属性,自动合成属性的 ivar 仍然为零?
【发布时间】:2013-12-09 15:58:07
【问题描述】:

我发现了一个奇怪的问题。

在此示例中,Xcode 5.0.2 和 iOS 7.0 在“iPhone Retina(4 英寸)”模拟器上发生了一些不可能发生的事情。

UIView 子类中的一个属性被定义为:

@property (nonatomic, strong) EAGLContext *context;

没有自定义的 getter 或 setter。所以应该创建_context ivar。

似乎 ivar 存在,但是当我分配某些东西时,ivar 仍然为零。

self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];

// breakpoint:
// "po [self context]" returns proper object.
// "po _context" returns nil

这怎么可能?

为了排除冲突,我将属性重构为“context123”,但结果相同。 LLDB 调试器会说 _context123 为 nil。

我会马上回答这个问题。这是一个有趣的问题,其他人可能会觉得很有用。

【问题讨论】:

    标签: ios objective-c properties


    【解决方案1】:

    原因是子类不小心覆盖了这个属性。这会导致在子类中创建一个冲突的 ivar,其值会影响超类中的 ivar。

    【讨论】:

    • 好收获。我刚刚因为“神奇”的持续零而失去了一个小时。为了增加混淆,似乎可以从明显的 nil 属性中复制一个有效值。
    • @openfrog:在允许子类使用 ivar 的同时解决这个问题的最佳方法是什么?
    猜你喜欢
    • 2020-12-23
    • 2011-05-03
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2011-07-24
    • 1970-01-01
    相关资源
    最近更新 更多