When to use strong or weak for properties

妖精的绣舞 提交于 2019-12-10 10:53:14

问题


I have a table view as an IBOutlet, and by default XCode sets its property to be strong rather than weak. Sometimes I get a "recieved memory warning" message. So I tried to change many properties from strong to weak, but it doesn't seem to affect the process and things work smoothly. Should I set the outlets to weak, or am I wrong?

And most importantly, should I set ALL properties to nil in the viewDidUnload method, or only the IBOutlets?


回答1:


You should set only Strong properties to nil in viewDidUnload. Weak Properties are automatically set to Nil if the destination object is deallocated.

IBOutlet can be set to strong or weak based on the requirement.

For the warning issue you are facing can you provide more details and code?

Apart from link provided by Josh, there are a lot of posts on SO related to this topic, some are below:

weak or strong for IBOutlet and other

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

Good detailed explanation can be found here:

http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1

Apple docs on this topic can be found here: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html#//apple_ref/doc/uid/TP30001163-CH17-SW1




回答2:


"When a parent has a reference to a child object, you should use a strong reference. When a child has a reference to its parent object, you should use a weak reference"

In general weak references are used when you deal with memory cycles. if you use strong you need to set nil in viewDidUnload since if you don't do it, in memory low conditions, you could cause unexpected leaks. You don't release them in dealloc because ARC will do it for you. weak instead doesn't need that treatment since, when the target object is destroyed, those values are set as nil automatically. No dangling pointers anymore.



来源:https://stackoverflow.com/questions/11373546/when-to-use-strong-or-weak-for-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!