I’m confused on what the proper way to write custom init methods for youw own subclass in terms of memory management, custom subclasses, and arrays. If I have properties like:
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) SomeSubclassOfNSObject *object;
@interface SomeSubclassofNSObject
@property (nonatomic, retain) NSString *category;
How do I write my init method?
do you do:
initWithName:(NSString *)aName object:(SomeSubclassOfNSObject *)anObject {
if (self = [super init]) {
self.name = aName; // or do you do name = aName or name = [aName copy] autorelease] or name = [NSString alloc] initWithFormat:@"%@", aName]
self.object = anObject; // do I need to make a copy of this object so they don't point to the same object?
// loop through NSMutableArray and copy the objects?
// not really sure what to do for arrays.
}
return self;
}
I would recommend
self.name = aName;in most cases because this takes advantage of the generated setter and thus the retain count is incremented implicitly. That means your reference is safe whatever the caller ofinitwill do afterwards withaName. The same applies to the dealloc counterpart: just writeself.name = nil;and your done.Things are different if you are supplying
NSMutableStringbecause changes inside of your class will affect other classes’ references to this. But from design view mutable strings should be used as paramters only if it’s your intention that they are manipulated.self.object = anObject;: Well it depends what you want. If all classes should point to the same object don’t make copy (I think this is most often exactly what you want). There might be cases when it is reasonable to make a deep copy.Arrays: You need something like
array = [[NSMutableArray alloc] init];in your init method. Afterwards the retain count will be incremtented automatically for every object you add i.e. you must not call retain on the added object itself. Like in 2. there might be situations where you really want to have copies of the objects of some source array. OK do it but this is rarely the case.More often you have an existing array and want a sub-array of it or a special sorted version. So you have got a new array but the same elements.
This was the short answer. More about this in:
Advanced Memory Management Programming Guide
Declared Properties