从init方法调用一个方法?
说我有两个属性定义如下:
@property (nonatomic, strong) UITableView *parentTableView; @property (nonatomic, strong) NSMutableArray *headersArray;
和一种方法:
-(void)prepareTags;
并说我有一个像这样的init方法:
-(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; }
- 这是在init方法中设置标题数组的正确方法吗?
- 我允许从init方法调用
self.parentTableView
? - 我是否允许从init方法中调用一个方法(在这种情况下,prepareTags方法也调用它
self
,即使init方法还没有返回,self
是否准备好使用?
分别(我会使用列表格式,但我不能使它与块引用…!):
这是在init方法中设置标题数组的正确方法吗?
是的,但有没有array
variables,你可能也只是这样做: headersArray = [[NSMutableArray alloc] init];
我允许从init
方法调用self.parentTableView
?
不,请引用“实用内存pipe理”中的Apple文档 :
不要在初始化方法中使用访问器方法和dealloc
。 你应该直接访问伊娃(就像你使用headersArray
)
我是否允许从init
方法中调用一个方法(在这种情况下, prepareTags
方法也调用它self
,即使init
方法还没有返回, self
是否准备好使用?
是。 只要非常小心(你的对象可能还没有完全初始化,它不应该使用访问器方法,以符合以前的限制,等等)
这里不需要使用局部variables:
NSMutableArray *array = [[NSMutableArray alloc] init]; headersArray = array;
直接分配给实例variables:
headersArray = [[NSMutableArray alloc] init];
我允许从init方法调用self.parentTableView?
是的,虽然有些人可能会认为这是糟糕的devise。 考虑一下这样一个事实,即属性有时会具有非显而易见的复杂的setter方法来查看其他实例variables。 当你的对象没有被完全初始化的时候这样做是明智的吗?
我允许从init方法调用一个方法吗?
同上。 只要你不依赖任何你还没有初始化的东西,那也没关系。
代码看起来不错。 只是几个笔记…
-(id)initWithParentTableView:(UITableView*)parentTable { // avoid compiler warning about the assignment and the condition in the same statement self = [super init]; if(self) { //1 // no need for the extra stack variable self.headersArray = [[NSMutableArray alloc] init]; //2 // this is all fine from here self.parentTableView = parentTable; //3 [self prepareTags]; } return self; }