Set to nil in viewDidUnload, but release in dealloc

来源:互联网 发布:海岛奇兵火箭炮手数据 编辑:程序博客网 时间:2024/06/05 05:55

code sample should look like the following:

- (void)viewDidUnload {    self.label = nil;    [super viewDidUnload];}- (void)dealloc {    [label release];    [super dealloc];}

When a low-memory condition occurs and the current viewcontroller’s views are not needed, the system may opt to removethose views from memory. This method is called after the viewcontroller’s view has been released and is your chance to performany final cleanup. If your view controller stores references to theview or its subviews, you should use this method to release thosereferences (if you retained the objects initially) and set thosereferences to nil. You can also use this method to release anyobjects that you created to support the view but that are no longerneeded now that the view is gone. You should not use this method torelease user data or any other information that cannot be easilyrecreated.

Typically, a view controller stores references to objects using anoutlet, which is a variable or property that includesthe IBOutlet keyword and isconfigured using Interface Builder. A view controller may alsostore pointers to objects that it creates programmatically, such asin the viewDidLoad method.The preferred way to relinquish ownership of any object (includingthose in outlets) is to use the corresponding accessor method toset the value of the object to nil.However, if you do not have an accessor method for a given object,you may have to release the object explicitly.

dealloc:在对象被销毁后被调用。

 a pointer to a deallocated object is verydifferent than one to nil. The former is a pointer to garbagememory, and you will almost certainly crash if you attempt to doanything with it (such as calling -release onit). A pointer to nil, on the other hand, is safe. It will silentlyignore any message sent to it. Saying idfoo = nil; [foo doSomething]; will justskip the call to -doSomething entirely.If you release an obj in -viewDidUnload,but don't nil it out, you'll crash when you try to release it againin-dealloc,or if you use self.foo= somethingElse

In general, use self.label everywhereoutside of -init-dealloc,and a custom getter/setter. In those situations,use label.The self->label constructis really only useful inside of-copyWithZone: or,in some situations, inside blocks (typically properties will beused here though) and is considered bad formelsewhere
(关于这一点,官方的说法是:"Theonly places you shouldn’t use accessor methods to set an instancevariable are in init methods anddealloc.",关于原因比较靠普的说服有:
1、Apple discourages usingaccessors in init or dealloc, because they can have side effectsbeyond merely setting an instance variable. These are obviouslyundesirable in an uninitialized or destroyed object.
在init和dealloc中,对象的存在与否还不确定,所以给对象发消息可能不会成功)

0 0