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

标签 ios objective-c uitableview delegates datasource

我正在学习 Objective-C,我在我的书中发现了以下代码。我有 3 个问题,

  1. 显然,它通过实现两个必需的方法来符合协议(protocol),但为什么不用写 <UITableViewDataSource,UITableViewDelegate> 就可以工作?在标题中?
  2. 它符合哪个协议(protocol),UITableViewDataSourceUITableViewDelegate
  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) initWithStyle:(UITableViewStyle)style
{
    return [self init];
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[[ItemStore sharedStore] allItems] count];
}
-(UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)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

感谢您帮助理解这一点。

最佳答案

<强> 1. Obviously it conforms the protocol by implementing two required methods, but why this works without writing '<'UITableViewDataSource,UITableViewDelegate'>' in the header?

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

<强> 2. Which protocol it conforms, UITableViewDataSource or UITableViewDelegate?

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

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;

<强> 3. Why there is no UITableView.delegate = self?

就在那里,检查你的xib您也从 xib 设置了委托(delegate)。右键单击UITableView你就会明白我的意思,如果不设置委托(delegate),上述方法将不起作用。

希望这有帮助。

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

相关文章:

iOS UIView 不调整 subview 的大小?

iphone - 如何dequeueReusableCellWithIdentifier : work?

ios - 如何使用 UIKit 在 Swift 5 中没有任何第三方库的情况下在 iOS 应用程序中使用 GIF?

objective-c - 与一个实体有多种关系而没有反向?

objective-c - NSTimer 没有运行选择器?

ios - 用于自定义 UIVIew 的 UI_APPEARANCE_SELECTOR

ios - UISearchBar搜索功能不起作用

ios - 在 UITableview 的页脚底部添加一个按钮

ios - SharedApplication.openUrl 隐藏自己的应用程序

ios - 对 SceneKit 中相机的正交投影感到困惑