Hello,
by doing more and more Objective-C I somehow get more and more confused about memory management. I have read the according document but what I need are some best practice examples. Here I have a small example class and a couple of questions.
Are there any other helpful guides / documents explaining how to write custom classes?
Code:
@interface MyClass : NSObject {
NSString *name;
CoolObject *coolObject;
}
@property (readonly, retain) NSString *name;
@property (readwrite, retain) CoolObject *coolObject;
- (id)initWithName:(NSString *)theName;
- (void)doWhatever;
@end
@implementation MyClass
@synthesize name, coolObject;
// custom initializer
- (id)initWithName:(NSString *)theName {
if (self = [super init]) {
name = theName;
coolObject = [[CoolObject alloc] init];
}
return self;
}
// overwrite setter
- (void)setName:(NSString *)theName {
if (theName != nil && [theName length] > 0) {
name = theName;
}
}
// overwrite setter
- (void)setCoolObject:(CoolObject *)theObject {
if (theObject != nil) {
coolObject = theObject;
}
}
- (void)doWhatever {
self.coolObject = [[CoolObject alloc] init];
}
- (void)dealloc {
[name release];
[coolObject release];
[super dealloc];
}
@end
1. should a NSString property be assigned, retained or copied? What are best practices? Or when should I chose which?
2. in the custom initializer:
Is there a leak assigning the object?
Would this be better?
CoolObject *tmp = [[CoolObject alloc] init];
coolObject = tmp;
[tmp release];
What about the method doWhatever? Does this leak an object?
should it rather be:
[coolObject release];
CoolObject *tmp = [[CoolObject alloc] init];
self.coolObject = tmp;
[tmp release];
3. overwritten setters: is there a call of [name release] / [coolObject release] missing before the assignment?
4. dealloc: is it correct that
coolObject = nil;
is similiar to
[coolObject release];
coolObject = nil;
Thanks!