使用“分配”创建属性时将其设置为 nil

发布于 2024-12-09 11:24:48 字数 174 浏览 3 评论 0原文

如果我创建一个具有“分配”属性的属性,在 dealloc 方法中将该属性设置为 nil 会发生什么

@property (nonatomic, assign) NSString* myData;

- (void)dealloc {
    self.myData = nil;
}

What happens if I create a property with "assign" attribute set the property to nil in dealloc method

@property (nonatomic, assign) NSString* myData;

- (void)dealloc {
    self.myData = nil;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

森罗 2024-12-16 11:24:48

然后调用 setter,它只是将指针设置为 nil,而不会发生其他任何事情。

编辑:(非原子,分配)和(非原子,保留)之间的区别

分配 -属性只会设置指针和保留 -属性还将对旧对象调用release并在新对象上调用retain。

合成的 (nonatomic, allocate)-setter 将如下所示:

-(void) setMyData:(NSString*)value
{
    myData = value; //just assigning the pointer
}

合成的 (nonatomic, keep)-setter 将如下所示:

-(void) setMyData:(NSString*)value
{
    [value retain];   // retain new object
    [myData release]; // release old object. if myData is nil: nothing happens
    myData = value;   // assigning the pointer
}

在 getter 之间没有区别。两者都只是非原子的。

then the setter is called which just sets the pointer to nil and nothing else happens.

edit: difference between (nonatomic, assign) and (nonatomic, retain)

An assign-property will only set the pointer and a retain-property will also call release on the old and retain on the new object.

The synthesized (nonatomic, assign)-setter will look like this:

-(void) setMyData:(NSString*)value
{
    myData = value; //just assigning the pointer
}

And the synthesized (nonatomic, retain)-setter will look like this:

-(void) setMyData:(NSString*)value
{
    [value retain];   // retain new object
    [myData release]; // release old object. if myData is nil: nothing happens
    myData = value;   // assigning the pointer
}

Between the getters there is no difference. Both are just nonatomic.

黯然#的苍凉 2024-12-16 11:24:48

这样做并没有什么错。

这样做通常没有任何好处。除非在 dealloc 中运行更多代码(具体取决于 myData 的值),否则它将不会产生任何影响。

当您将声明和定义为保留的属性设置为 nil 时,它会导致将释放发送到先前的属性值。但当它被定义为分配时,这种情况就不会发生。它基本上只是设置实例变量,这通常在 dealloc 中并不重要,因为没有其他东西会读取实例变量的值。

There is nothing wrong with doing that.

There is normally no benefit to doing that. It will have no effect, unless some more code in dealloc runs after that that depends on the value of myData.

When you set a property declared and defined as retain to nil, it causes release to be sent to the previous property value. But when it's defined as assign, that doesn't happen. It basically just sets the instance variable, which normally doesn't matter in dealloc since nothing else is going to read the value of the instance variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文