我正在学习 Objective-C,我在我的书中发现了以下代码。我有 3 个问题,
- 显然,它通过实现两个必需的方法来符合协议(protocol),但为什么不用写
<UITableViewDataSource,UITableViewDelegate>
就可以工作?在标题中? - 它符合哪个协议(protocol),
UITableViewDataSource
或UITableViewDelegate
? - 为什么没有
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/