How to use dealloc when dealing with auto-synthesized properties?

不打扰是莪最后的温柔 提交于 2019-12-24 08:57:36

问题


I'm relatively new to iOS development so please excuse me if this is a retarded question. I've read this but am still a bit confused.

I'm not using ARC. (Yes yes, I know I should but I don't at this point) In my class header I have this

/*-----------------------------------------------------------------------+
 | The name of the sender/receiver
 +-----------------------------------------------------------------------*/
@property (nonatomic, retain) NSString *name;

I do NOT synthesize this variable but let the compiler do that job.

What of the following is considered to be best practise for the dealloc method

#1 Dealloc the iVar

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

#2 Dealloc the property

-(void) dealloc {
   [self.name release];
   [super dealloc];
}

#3 And a last question. Is is customary to set the property to nil in the dealloc method? I.e.

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

Would really appreciate if someone could explain this to me.

Regards!


回答1:


Jeff Lamarche has written a nice article about releasing variables in the dealloc: http://iphonedevelopment.blogspot.nl/2010/09/dealloc.html

He suggest never to use the self. syntax, since it can cause problems in a multi threaded environment.

His suggestion is to use the iVar and set in to nil in production builds:

-(void) dealloc {
   [_name release], _name = nil;
   [super dealloc];
}



回答2:


Approach 1:

It's safe to use it. There is no harm in releasing the iVar in dealloc method. However, when you have assigned the value to name, it must be through property or through alloc method(not the factory method).

Approach 2:

At the time of release, do not use properties.

Approach 3:

Do not use property but you can surely assign nil to ivar.



来源:https://stackoverflow.com/questions/15107440/how-to-use-dealloc-when-dealing-with-auto-synthesized-properties

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