0

我正在读一本书,它教导我们应该实现一个指定的类初始化器,然后让其他初始化器调用这个(我同意)。

现在,我在这本书的一节中,它说:“UITableViewController 的指定初始化程序是 initWithStyle:”。然后像这样进入实现:

// inside ItemsViewController.m, subclass of UITableViewController

-(id) init{
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    return [self init];
}

在这段代码之后,书中还说:“这将确保 ItemsViewController 的所有实例都使用 UITableViewStyleGrouped 样式,无论向它发送什么初始化消息。”

为了坚持我在文章开头描述的原则,我可能会这样实现这个类:

// inside ItemsViewController.m, subclass of UITableViewController


// Implement the designated initializer first
-(id) initWithStyle:(UITableViewStyle)style
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self;
}

// Call designated initializer
- (id)init
{
    return [self initWithStyle: nil];
}

但我想我错过了什么?我认为这本书init在他们的情况下用作指定的初始化程序?

4

3 回答 3

0

Basically your code and the code in the book do the same thing. there are different types of initializers for classes, you use the one you need. What the example in the book wants to show you is how to overwrite them if you need some custom initializers later on. Sow it's understandable that it doesn't really make sense from a real live application point of view but from a learning overwriting initializers and customization i think it's ok.

于 2013-07-29T09:20:01.857 回答
0

Construction

// Implement the designated initializer first
-(id) initWithStyle:(UITableViewStyle)style
    // Call the superclass's designated initializer
    self = [super initWithStyle:UITableViewStyleGrouped];
    if (self) {

    }
    return self; }

is confusing for user of class, because he will think that you provided initWithStyle constructor to allow him setting controllers' style. You should use your first init method.

于 2013-07-29T09:04:58.597 回答
0

如果您有自定义的 tableviewcell 类,那么您不需要实现 initwithstyle 初始化程序,并且不会为原始对象和类成员对象调用该初始化程序。您将不得不忍受。所以请遵循标准初始化程序。

于 2013-07-29T09:00:41.573 回答