OGeek|极客世界-中国程序员成长平台

标题: ios - 为什么 View Controller 的 header 中没有协议(protocol)声明? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 07:00
标题: ios - 为什么 View Controller 的 header 中没有协议(protocol)声明?

我正在学习objective-c,并在我的书中找到了以下代码。我有 3 个问题,

  1. 显然它通过实现两个必需的方法来符合协议(protocol),但是为什么不在 header 中编写 就可以工作?
  2. 它符合哪个协议(protocol),UITableViewDataSource 还是 UITableViewDelegate
  3. 为什么没有UITableView.delegate = self

这是代码,

@implementation ItemsViewController

-(instancetype) init
{
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        for (int i = 0; i < 5; i++)
        {
            [[ItemStore sharedStore] creatItem];
        }
    }
    return self;
}
-(instancetype) initWithStyleUITableViewStyle)style
{
    return [self init];
}

-(NSInteger) tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section
{
    return [[[ItemStore sharedStore] allItems] count];
}
-(UITableViewCell *) tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath
{
    UITableViewCell *c = [tableView dequeueReusableCellWithIdentifier"UITableViewCell" forIndexPath:indexPath];
    NSArray *items = [[ItemStore sharedStore] allItems];
    Item *item = [items objectAtIndex:indexPath.row];
    c.textLabel.text = [item description];
    return c;
}

-(void) viewDidLoad
{
    [super viewDidLoad];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier"UITableViewCell"];
}

@end

感谢您帮助理解这一点。



Best Answer-推荐答案


1。显然它通过实现两个必需的方法来符合协议(protocol),但是为什么在标题中不写 '<'UITableViewDataSource,UITableViewDelegate'>' 就可以工作?

标题中的 '<'UITableViewDataSource,UITableViewDelegate'>' 只是向编译器表明你想在你的类中实现委托(delegate)方法。如果您不实现标记为 @required 的委托(delegate)方法,您将收到警告,但由于大多数委托(delegate)方法通常是 @optional 您的代码将编译并运行美好的。这并不意味着您不应该在标题中添加委托(delegate)。

2。它遵循哪个协议(protocol),UITableViewDataSource 还是 UITableViewDelegate?

默认只需要UITableViewDataSource 必须定义这两个函数

-(NSInteger)tableViewUITableView *)tableView numberOfRowsInSectionNSInteger)section;


-(UITableViewCell *)tableViewUITableView *)tableView cellForRowAtIndexPathNSIndexPath *)indexPath;

3。为什么没有 UITableView.delegate = self?

它在那里,检查你的 xib 你也从 xib 设置了委托(delegate)。右键UITableView你就会明白我的意思了,不设置委托(delegate)上面的方法都行不通。

希望这会有所帮助。

关于ios - 为什么 View Controller 的 header 中没有协议(protocol)声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497217/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4