Objective-C 发布后是否需要将指针设置为 nil?
做类似的事情有什么问题吗
NSString * string = [ [ NSString alloc ] init ];
<代码>...[字符串释放];
或者添加还有什么价值(除了最佳实践之外)
字符串 = nil;
?
Is there anything wrong with doing something like
NSString * string = [ [ NSString alloc ] init ];
...
[ string release ];
or is there any value (other than best practice) in also adding
string = nil;
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是必需的,但很好的做法。 如果你在发布后不经意地引用它,可能会发生不好的事情,但在 Objective C 中引用 nil 没有任何坏处。
Not necessary, but good practice. If you were to inadvertently reference it after release, bad things could happen, but in Objective C there isn't any harm in referencing a nil.
将实例变量设置为 nil 在多线程应用程序中比在单线程应用程序中更有用,因为在多线程中,您无法始终保证实例变量仅在释放之前被读取。
我通常不会在单线程应用程序中烦恼,除非有其他令人信服的原因。
Setting an instance variable to nil is more useful in a multi-threaded application than a single-threaded one, since with multiple threads you can't always guarantee that an instance variable will only be read before it's released.
I generally don't bother in single-threaded applications, unless there's some other compelling reason.
Objective-C 实际上与 C 相同,但具有精美的预处理器。
在 Objective-C 中将指针设置为 nil 对该指针曾经指向的内容没有影响。
Objective-C is really the same as C with a fancy preprocessor.
Setting a pointer to nil in Objective-C has no effect on what was once pointed to by that pointer.