在Objective C中的synchronized块中设置实例变量

Enr*_*tyo 0 synchronization objective-c

我有一个同步的函数,但似乎我无法直接更改该块中的实例变量的值.

+(id)allocWithZone:(NSZone *)zone
{
@synchronized(self) {
    if (sharedInstance == nil) {
        sharedInstance = [super allocWithZone:zone];

        //This is not allowed
        something = @"hello";

        //This is allowed
        self.something = @"hello world!";

        return sharedInstance;
    }
}

return nil;
}
Run Code Online (Sandbox Code Playgroud)

为什么会这样?我有一个我需要直接访问的变量(我不想合成该变量).我该如何解决这个问题?

Lil*_*ard 5

您无法更改实例变量,因为这不是实例方法.self事实上,价值就是阶级本身.您的代码行self.something = @"hello world!"也不起作用.你真正想要的是sharedInstance.something = @"hello world!",只有something属性才会有效.更好的方法是在init方法中设置ivars.

哦,+allocWithZone:无论如何你都没有设置ivars的业务.该对象尚未初始化.

假设你试图在这里创建一个单例(就像它看起来那样),你可能想要阅读这篇关于Obj-C中单例的博客文章.