12

I have noticed a little confusion when looking at various bits of code both in books and on the web when it comes to implementing dealloc. My question is when using @property which of the following should I be using. Up until now I have been using VERSION_001.

@property(nonatomic, retain) NSString *name;
@property(nonatomic, retain) NSString *type;
@property(nonatomic, retain) NSString *payload;
@property(nonatomic, retain) NSString *orbit;

VERSION 001

- (void)dealloc {
    [name release];
    [type release];
    [payload release];
    [orbit release];
    [super dealloc];
}

VERSION 002

- (void)dealloc {
    [self setName:nil];
    [self setType:nil];
    [self setPayload:nil];
    [self setOrbit:nil];
    [super dealloc];
}
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421
fuzzygoat
  • 26,573
  • 48
  • 165
  • 294

1 Answers1

17

There is no real difference, Unless you are not using the @synthesize keyword. When you set the properties to nil, they are being released behind the scenes by the setter. Now, there may be a slight performance increase over the fist version, because not so much needs to happen behind the scenes (e.g. pointer comparison, and everything else apple hides behind the scenes). I always use version 001, because it is more to the point and future developers don't have to dig though my code to figure out what I am accomplishing.

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • Thank you, just what I was after, much appreciated. – fuzzygoat Nov 08 '10 at 13:16
  • 3
    A big advantage that version 1 has over version 2 is that if some day you modify the setter for one of these properties to do some non-trivial work, you will not incur the performance or potential incorrect behavior in version 1. Version 2 could easily cause you to introduce bugs in your code without realizing it some day down the road. – Ryan Nov 08 '10 at 19:28
  • 2
    Conversely, an advantage (I hesitate to say 'big') of version 2 over version 1 is that you can change your properties freely between assign and retain without having to change your dealloc. Setting the property to nil then becomes 'release this if needed'. Though since Cocoa conventions on when to retain and when to assign are quite straightforward, I don't see this being an issue very often. – Tommy Nov 09 '10 at 00:41
  • VERSION 002 is that little bit more safe as it prevents memory errors when releasing properties that have already been deallocated (which would be a programming error but the point still holds). – Willster Jan 31 '11 at 13:39
  • @Willster, tommy has already stated that. However, the disadvantage to that is if using the @synthesize keyword, some (however light) performance will be lost. At run-time, it will be minimal, but there nevertheless. – Richard J. Ross III Jan 31 '11 at 14:48