Reputation: 9243
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
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
Reputation: 62686
A few things:
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