Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method from the init method?

Say I have two properties defined as such:

@property (nonatomic, strong) UITableView *parentTableView;
@property (nonatomic, strong) NSMutableArray *headersArray;

and a method:

-(void)prepareTags;

and say I have an init method like this:

-(id)initWithParentTableView:(UITableView*)parentTable
{
    if(self = [super init])
    {
        //1
        NSMutableArray *array = [[NSMutableArray alloc] init];
        headersArray = array;
        //2
        self.parentTableView = parentTable;
        //3
        [self prepareTags];
    }
    return self;
}
  1. Is this the correct way to set up the headers array in an init method?
  2. Am I allowed to call self.parentTableView from the init method?
  3. Am I allowed to call a method from the init method (in this case, the prepareTags method calls self too. Will self be ready to use, even though the init method hasn't returned yet?
like image 216
Snowman Avatar asked Oct 29 '25 17:10

Snowman


1 Answers

Respectively (I'd use list formatting but I can't make it work with blockquotes...!):

Is this the correct way to set up the headers array in an init method?

Yes, but there's no point having the array variable, you might as well just do: headersArray = [[NSMutableArray alloc] init];

Am I allowed to call self.parentTableView from the init method?

No, to quote the Apple docs on Practical Memory Management:

Don’t Use Accessor Methods in Initializer Methods and dealloc

. You should access the ivar directly (as you do with headersArray)

Am I allowed to call a method from the init method (in this case, the prepareTags method calls self too. Will self be ready to use, even though the init method hasn't returned yet?

Yes. Just be very careful (your object may not have been fully initialised, it shouldn't use accessor methods so as to comply with the previous restriction, et cetera)

like image 152
Kristian Glass Avatar answered Oct 31 '25 08:10

Kristian Glass



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!