Zain Syed
Zain Syed

Reputation: 44

I intend to call default init method in init method with arguments

I intend to call default init method in init method with arguments, in iOS. like this:

-(id)init{
    self = [super init];
    if (self) {
        Office =          [[NSString alloc]init];
    }
    return self;
}

-(id)initWithOffice:(NSString*)office{
    self = [self init];
    if (self) {
        self.Office = itemDescription;
    }
    return self;
}

My question is it a good practice, What should be done? I appreciate your response in advance,

Upvotes: 0

Views: 246

Answers (3)

Prateek Prem
Prateek Prem

Reputation: 1544

I think you should improve you object assignning logic,Like that...

-(id)initWithOffice:(NSString*)office{
    self = [self init];
    if (self) {
        self.Office =  [[NSString alloc] initWithString:office]; //Purpose is that //the office object can only be released by the self, non other classes (The owner //of the variable should be self).
    }
    return self;
}

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122458

That will work, but I would prefer the following as it doesn't allocate an empty string, only to be replaced with the initializing string:

-(id)initWithOffice:(NSString*)office{
    self = [super init];    // Not [self init]
    if (self) {
        Office = office;    // OK if using ARC
    }
    return self;
}

The first init method doesn't make a great deal of sense; I think simply leaving Office as nil is better (NSString objects are immutable). As pointed out by @H2CO3, the initWithOffice method becomes the designated initializer for the class and all other init methods should use it to initialize the object. With that in mind the first init method should be:

-(id)init{
    return [self initWithOffice:nil];
}

Upvotes: 5

Engnyl
Engnyl

Reputation: 1380

Creating a method starts with initWith is to see what values will be passed. It helps you to remind which values should be sent and allocated in the method. Consider you have 4 variables to init when the view is initialized. It's best to keep a separate initWith method where you can init your view and other variables you customize.

Upvotes: 1

Related Questions