【问题标题】:When using ARC, property values are automatically getting set to nil after being assigned a non-nil value使用 ARC 时,属性值在被分配一个非 nil 值后会自动设置为 nil
【发布时间】:2014-03-22 08:06:24
【问题描述】:

我在编写 Mac OS X 程序时使用 ARC,但遇到了一个有趣的问题。我的 .h 文件包含以下几行:

@property Profile *profile;

 (void) setProfile:(Profile *) newProfile;

 (Profile *) profile;

变量profile在.h中声明如下:

Profile *profile;

我的 .m 文件具有以下属性实现:

(void) setProfile:(Profile *) newProfile
{
    profile = newProfile;

    if (profile)
    {
        [profileNameTextField setStringValue:profile.name];        
    }
 }

(Profile *) profile
{
    return profile;
}

setProfile 方法效果很好,profile 被设置为非零值。问题是当 .m 文件中的其他方法尝试访问配置文件时,配置文件为 nil。有谁知道我可能做错了什么?我变了

@property Profile *profile;

@property (nonatomic, strong) Profile *profile;

仍然没有运气。谢谢大家。

【问题讨论】:

  • 这甚至不会编译。请发布您正在使用的实际代码。

标签: objective-c macos properties automatic-ref-counting null


【解决方案1】:

我的猜测是变量名有冲突。拥有一个属性并且它支持的 ivar 具有相同的名称是一种不好的做法。我不确定 10%,但您的代码可能会被解释为具有两个不同的“个人资料”成员。

如果在您的代码中使用

 x = profile;  // access to the variable
 x = self.profile // access the property

通常,支持属性的变量以 _ 为前缀,因此默认情况下,属性 profile 以名为 _profile 的变量支持。

您可以通过使用 @synthesize 关键字显式设置支持变量来覆盖默认行为。

我会删除profile 变量并离开该属性。还要在 getter 和 setter 中将 profile 替换为 _profile,如果编译器仍然报错,请使用 @synthesize。

【讨论】:

    猜你喜欢
    • 2023-03-18
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多