Sean Danzeiser
Sean Danzeiser

Reputation: 9243

Objective C initializer basics

I have a question about initializers that overlaps with memory management. I'm confident that this is a perfectly functional initializer (even tho it calls setters in the init method which is discouraged) . . .

@synthesize age = _age, name = _name, delegate = _delegate;

- (id)initWithName:(NSString *)name Age:(int)age delegate:(MyDelegateClass *)delegate
{
    if (self = [super init]) {

        [self setName:name];
        [self setAge:age];
        [self setDelegate:delegate];
     }

  return self;

}

But what about this initializer? Do i need to allocate memory for those ivars or does it just work out of the box like this?

- (id)initWithName:(NSString *)name Age:(int)age delegate:(MyDelegateClass *)delegate
{
    if (self = [super init]) {

        _name = name;
        _age = age;
        _delegate = delegate;
     }

  return self;

}

Upvotes: 1

Views: 483

Answers (2)

Caleb
Caleb

Reputation: 125037

Normally, you'll want to copy strings rather than assign them -- even though you've specified that name is an NSString*, the object it points to might actually be a NSMutableString. So do this:

_name = [name copy];

Upvotes: 1

danh
danh

Reputation: 62686

A few things:

  1. (void) return type won't work. Make it (id)
  2. compiler will warn on the assignment in the conditional, use two lines
  3. it's common practice to set ivars directly in init, not referring to self*
  4. neither of your forms you suggest allocate memory. that's done when the object is allocated.

so ...

- (id)initWithName:(NSString *)name age:(int)age delegate:(MyDelegateClass *)delegate {

    self = [super init];
    if (self) {
        _name = name;
        _age = age;
        _delegate = delegate;
    }
    return self;
}

Upvotes: 1

Related Questions