Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Object Initialization in Objective-C

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!

like image 633
darksky Avatar asked Jun 28 '11 10:06

darksky


People also ask

How do you initialize an object in Objective-C?

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.

How do you allocating and initializing objects?

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.

What is self super init?

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.


1 Answers

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"];
}
like image 54
JeremyP Avatar answered Sep 23 '22 17:09

JeremyP