2

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!

Groot
  • 13,943
  • 6
  • 61
  • 72

2 Answers2

2

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];
}
rckoenes
  • 69,092
  • 8
  • 134
  • 166
  • 2
    Also getter is a perfect place for lazy initialization, you'll not want to start this process at `dealloc`. I used to have a macros for `-release, = nil` combination, it makes `dealloc` nice and clear. And here's an [answer](http://stackoverflow.com/a/1618867/792677) explaining `comma operator`. – A-Live Feb 27 '13 at 08:51
0

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.

Apurv
  • 17,116
  • 8
  • 51
  • 67