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!
Out of the box in Objective-C you can initialize an instance of a class by calling alloc and init on it. // Creating an instance of Party Party *party = [[Party alloc] init]; Alloc allocates memory for the instance, and init gives it's instance variables it's initial values.
An object can be allocated using the alloc instance method. This class method will allocate memory to hold the object and its instance variables and methods. However, allocation leaves memory undefined. So in addition, each object must be initialized, which sets the values of its data.
In the subclass (your class that you're working on) you call self = [super init] What this basically does is calls the super class's (the ones I mentioned above) init method (the constructor) and assigns it to the current class. This makes sure that the superclasses' initializing method is called.
Am I using retain here properly?
No you are not. You should either use
self.name = playerName;
as you suggested, or (as recommended by Apple)
name = [playerName copy];
It is not recommended to use accessors in -init
because subclasses might override them.
Also, note that as NSString
implements NSCopying
you should use a copy property, not a retain property.
Furthermore, assume I want another initializer, but keep the initWithName:playerName the designated initializer. How would I make the second initializer call the first?
Using -init
as an example (because you must override the super class's designated initialiser if your designated initialiser is not the same)
-(id) init
{
return [self initWithName: @"Some default value"];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With