iphone - 从 init 方法调用方法?

标签 iphone objective-c ios

假设我定义了两个属性:

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

和一个方法:

-(void)prepareTags;

然后说我有一个这样的初始化方法:

-(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. 这是在 init 方法中设置 header 数组的正确方法吗?
  2. 我可以从 init 方法调用 self.parentTableView 吗?
  3. 是否允许我从 init 方法调用方法(在这种情况下,prepareTags 方法也调用 selfself 是否可以使用,即使init方法还没返回?

最佳答案

分别(我会使用列表格式,但我不能让它与 block 引号一起使用......!):

这是在 init 方法中设置 header 数组的正确方法吗?

是的,但是拥有 array 变量没有意义,您不妨这样做:headersArray = [[NSMutableArray alloc] init];

我可以从 init 方法调用 self.parentTableView 吗?

不,引用the Apple docs on Practical Memory Management :

Don’t Use Accessor Methods in Initializer Methods and dealloc

.您应该直接访问 ivar(就像您使用 headersArray 一样)

我是否可以从 init 方法调用方法(在这种情况下,prepareTags 方法也调用 self。将 self 准备好使用了,即使 init 方法还没有返回?

是的。请非常小心(您的对象可能尚未完全初始化,它不应该使用访问器方法以符合先前的限制,等等)

关于iphone - 从 init 方法调用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10289417/

相关文章:

ios - 在 UIImageView 中安装 UIImage

ios - 具有全局变量的共享实例

ios - UISegmentedControl 作为 UINavigationBar 标题项在一些延迟后加载

iphone - 引用 UIbutton 的 alpha 的 if/else 语句不起作用

iphone - 配置时没有为参数 'appIdName' 提供值

ios - 自动布局 : UITextFields with equal width in different UITableViewCells

iphone - 从 iOS 应用程序到 "Like"Facebook 页面还有更好的方法吗?

iphone - 如何: Save order of tabs when customizing tabs in UITabBarController

iphone - 检测图像中的特定对象,即使用 opencv 进行图像分割

ios - iOS 7中的Round Rect UIBarButton