Objective-C中的方法名称是相同的.

Man*_*ena 3 parameters methods objective-c naming-conventions uitableview

我的ViewController对象必须实现所需的表视图方法,以便它可以充当数据源.从UITableView.h:

@required  
-(NSInteger)tableView:(UITableView *)tableView
                       numberOfRowsInSection:(NSInteger)section;
-(UITableViewCell *)tableView:(UITableView *)tableView
                       cellForRowAtIndexPath:(NSIndexPath *)indexPath;
Run Code Online (Sandbox Code Playgroud)

这有点令人困惑.

第一个参数是什么(UITableView*)tableView,为什么它与方法名称相同?它看起来像是一个指向TableView对象的指针.为什么给它命名与方法相同?

其次,我理解虽然这看起来像重载,但实际上有两种方法,tableview:numberOfRowsInSectiontableView:cellForRowAtIndexPath.为什么是这样?

以下链接很有帮助.这里将提供任何其他帮助,特别是关于命名约定.

Objective-C中的方法重载?
Objective C中的函数重载是否可行?
如何在Objective-C中传递多个参数?

ico*_*ter 8

Objective-C方法旨在自我记录,并借鉴了Smalltalk的丰富传统.

我会试着解释一下你在这里有什么- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section.

  • - (NSInteger)
    第一部分表明这是一个返回NSInteger对象的Objective C 实例方法.的-(短划线)表示这是一个实例的方法,其中+将指示这是一种方法.括号中的第一个值是方法的返回值.

  • tableView:
    此部分是消息名称的一部分.在这种情况下,完整的消息名称tableView:numberOfRowsInSection:.Objective-C运行时获取此方法信息并将其发送到指示的接收器.在纯C中,这看起来像
    NSInteger tableView(UITableView* tableView, NSInteger section).但是,由于这是Objective-C,因此其他信息将打包到消息名称中.

  • (UITableView *)tableView
    这部分是输入的一部分.这里的输入是类型的,UITableView*并且具有tableView的局部变量名.

  • numberOfRowsInSection:
    此部分是消息名称的第二部分.正如您在此处所看到的,消息名称被拆分以帮助指示您传递给接收器的信息.因此,如果我是消息的对象myObject与所述变量myTablemySection,我想键入目标C样式:
    [myObject tableView:myTable numberOfRowsInSection:mySection];
    相对于C++式:
    myObject.tableView(myTable, mySection);.

  • (NSInteger)section
    这是输入的最后一部分.这里的输入是类型,NSInteger并具有局部变量名称section.