简体   繁体   中英

when to use self.property in init methods in objective-c, how to initialize arrays in init methods

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;
}
  1. 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 of init will do afterwards with aName . The same applies to the dealloc counterpart: just write self.name = nil; and your done.

    Things are different if you are supplying NSMutableString because 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.

  2. 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.

  3. 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 ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM