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;
}
- Is this the correct way to set up the headers array in an init method?
- Am I allowed to call
self.parentTableView
from the init method? - Am I allowed to call a method from the init method (in this case, the prepareTags method calls
self
too. Willself
be ready to use, even though the init method hasn't returned yet?
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 theinit
method?No, to quote the Apple docs on Practical Memory Management:
. 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, theprepareTags
method callsself
too. Willself
be ready to use, even though theinit
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)
The code looks pretty good. Just a couple notes...
There's no need to use a local variable here:
Just assign to the instance variable directly:
Yes, although some people might consider that poor design. Consider the fact that properties sometimes have non-obvious complex setter methods that look at other instance variables. Is it wise to do this when your object hasn't been fully initialised?
Same as above. So long as you aren't relying on anything you haven't initialised yet, it's fine.