• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 为什么 View Controller 的 header 中没有协议(protocol)声明?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 07:00:24 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在学习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/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap