gpt4 book ai didi

objective-c - 在 dealloc 中使用 self.property = nil 有什么问题吗?

转载 作者:太空狗 更新时间:2023-10-30 03:29:07 33 4
gpt4 key购买 nike

我知道声明的属性会生成访问器方法,这在某种程度上只是语法糖。

我发现很多人在他们的dealloc 方法中使用self.property = nil

1) 在 Apple 的 Memory Management 文档中,p23它说:

The only places you shouldn’t use accessor methods to set an instance variable are in init methods and dealloc.

为什么不应该?

2) 在苹果的 Objective-C 2.0, p74

Declared properties fundamentally take the place of accessor method declarations; when you synthesize a property, the compiler only creates any absent accessor methods. There is no direct interaction with the dealloc method—properties are not automatically released for you. Declared properties do, however, provide a useful way to cross-check the implementation of your dealloc method: you can look for all the property declarations in your header file and make sure that object properties not marked assign are released, and those marked assign are not released.

Note: Typically in a dealloc method you should release object instance variables directly (rather than invoking a set accessor and passing nil as the parameter), as illustrated in this example:

- (void)dealloc { [property release]; [super dealloc]; }

If you are using the modern runtime and synthesizing the instance variable, however, you cannot access the instance variable directly, so you must invoke the accessor method:

- (void)dealloc { [self setProperty:nil]; [super dealloc]; }

注释是什么意思?

我发现 [property release];[self setProperty:nil]; 都有效。

最佳答案

设置一个属性可以导致通知被发送到观察该属性的其他对象。这可能反过来导致那些对象试图对您的对象做进一步的事情。如果您正在解除分配,这可能不是您想要发生的事情。所以一般来说,直接release相关的实例变量会更安全。

请注意,这种问题只会在某些情况下出现,因此通常完全可以在 dealloc 中使用 self.property=nil 来编写代码,并针对所有情况锻炼得很好。这不是最佳实践。

在 Objective-C“现代运行时”中,可以在不指定 ivar 的情况下声明属性。运行时将合成存储以与合成的访问器一起使用。在这种情况下,您不能直接释放 ivar,因为就您的代码而言,没有一个。所以你别无选择,只能走 self.property=nil 路线。

关于objective-c - 在 dealloc 中使用 self.property = nil 有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5621139/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com