I have following simple class:
@interface Article: NSObject {
NSString *title;
}
@property (copy, nonatomic) NSString *title;
@end
@implementation
- (void)setTitle:(NSString *)aString {
if ((!title && !aString) || (title && aString && [title isEqualToString:aString])) return;
dirty = YES;
[title release];
title = [aString copy];
}
- (NSString *)title {
return title;
}
@end
In my application I have to do a lot of things like
Article *article= [objectsArray getObjectAtIndex:x]; NSString *title=article.title; UILabel.text=title; [title release];
I know I’m supposed to call retain when I get the property:
NSString *title=[article.title retain];
Maybe I am lazy to do a retain where I get the propery. Or If I need to do that tens of times all over the applicaiton.
Can I have getter to return a copy?
- (NSString *)title {
return [title copy];
}
There are some circumstances where I prefer to return a copy of the property for safety reasons. For example, if I’m writing a class that has a unique identifier property, then I’ll “return [[_uniqueID copy] autorelease]” so that there’s no chance that another class could do anything to the unique identifier. Other times I’ll just return the object itself, because it’s not a big deal if it’s externally manipulated.
Also, with respect to these getter methods, they should not return objects with a +1 retain count (which is what you have going). If anything, they should return the object directly or return it with a +0 retain count (retain/copy + autorelease). It greatly simplifies your memory management to do it that way. If the external object needs to hold on to the returned object, then the external object should be responsible for retaining whatever it needs.