views:

78

answers:

3

I am pretty sure I am doing this right, but just wanted to check. I have two instance variables that have accessors created via @property. In my dealloc (for the same object) I am releasing these objects.

@property(copy) NSString *firName;
@property(copy) NSString *surName;

-(void)dealloc {
    NSLog(@"_deal: %@", self);
    [firName release];
    [surName release];
    [super dealloc];
}

gary

A: 

Looks right. I'd usually use nonatomic, retain with NSString properties though...

EDIT: copy it is.

Malaxeur
The OP might be ensuring that no-one else modifies an NSString that's been past that's actually an NSMutableString.
Ben S
True. Although if this isn't the case, it should be switched to retain though, no need to for the pointless copy.
Malaxeur
Hi Ben, yes the idea was that I was creating a copy to protect against the original either being released or being modified.
fuzzygoat
bbum
Malaxeur: No, it should be copy. Never assume that everyone who passes you a string is going to pass you an immutable one. The only time it should be retain is if the type is `NSMutableString *` and you explicitly say that you will mutate the string passed in, and that's very unusual.
Peter Hosey
That's actually pretty informative. I was well aware that someone could have passed in an NSMutableString, however I wasn't aware that the copy is free... I had always assumed that it had a decent amount of overhead in comparison to retain (especially when you know that there will be no mutable strings).
Malaxeur
Not just NSString. Any of the other class cluster objects which have mutable/immutable counterparts, e.g. NSArray/NSMutableArray, NSDictionary/NSMutableDictionary. Calling copy on the them prevents the property being unexpectedly changed after it has been set. Also, it is efficient, because if the immutable value is used, the runtime just calls retain on the object instead of copying it. In that sense it is free because it doesn't generate unecessary overhead.
Abizern
+3  A: 

Yes, that's correct.

The implementation of the property will call release on the previous value before copying the new value, so the only memory management you have to worry about is releasing in the dealloc method, which you're doing.

Ben S
Thank you, much appreciated.
fuzzygoat
sidenote, couldn't he just use `self.firName = nil, self.surName = nil;`
Bryan McLemore
@Bryan: Yes, he could do that, but that's much less readable/maintainable than an easily understood `retain` call.
Ben S
A: 

That's correct. Remember the memory ownership policy. Since you're using copy, you gain ownership of the object as you would if you used retain, so you release when done.

Preston