I created a custom object in Objective-C. Now I want to create a custom initializer. The object has two properties, name and score. So my initializer is as follows:
- (id)initWithName:(NSString *)playerName {
if ((self = [super init])) {
self.name = [playerName retain];
self.score = [NSNumber numberWithInt:0];
}
return self;
}
Am I using retain here properly? Or can I just make it something like self.name = playerName;?
Furthermore, assume I want another initializer, but keep the initWithName:playerName the designated initializer. How would I make the second initializer call the first?
And for the last question, I know I need to override the - (id)init method too. However, what do I do there? Just assign test properties incase the class was initialized with init only?
Thank you!
No you are not. You should either use
as you suggested, or (as recommended by Apple)
It is not recommended to use accessors in
-initbecause subclasses might override them.Also, note that as
NSStringimplementsNSCopyingyou should use a copy property, not a retain property.Using
-initas an example (because you must override the super class’s designated initialiser if your designated initialiser is not the same)