3
4

3 回答 3

7

Objective-C 方法被设计为自我记录,它们借鉴了 Smalltalk 的丰富传统。

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

  • - (NSInteger)
    第一部分表明这是一个返回 NSInteger 对象的 Objective C实例方法。-破折号)表示这是一个实例方法,其中 a+表示这是一个方法。括号中的第一个值是方法的返回值。

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

  • (UITableView *)tableView
    这部分是输入的一部分。这里的输入是 type 的UITableView*,并且有一个 tableView 的局部变量名。

  • numberOfRowsInSection:
    这部分是消息名称的第二部分。正如您在此处看到的,消息名称被拆分以帮助指示您传递给接收者的信息。因此,如果我要myObject使用变量myTable和向对象发送消息mySection,我会输入Objective-C 风格:
    [myObject tableView:myTable numberOfRowsInSection:mySection];
    而不是C++ 风格:
    myObject.tableView(myTable, mySection);

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

于 2013-05-27T04:39:34.600 回答
3

没有重载,因为方法名称不一样

tableView:numberOfRowsInSection:
tableView:cellForRowAtIndexPath:

包括 :, : 很重要,也是名称的一部分,

参数是:'s 之后的部分,:'s 之前的部分是方法名的一部分,方法名是参数交织在一起。

所以你的两个方法有两个参数,第一个是调用该方法的表视图。

一旦你理解了这一点,在它后面的方法名称部分之后命名参数是很自然的。

于 2013-05-27T04:59:52.767 回答
2

Apple (and other SDK developers) frequently name their variables being passed the same names as the API parameters. To some folks, it just makes readability a little easier.

I mean, for the UITableViewDataSource methods, the first parameter is named for the table view for which we're getting the data for. And the variable passed into this method is also named "tableView", so if the object serving as a data source has more than one table to serve up data for, that object will know which specific table is doing the requesting.

This happens a lot in delegate methods. Take a look at the UITextFieldDelegate methods, for example. When you have more than one text field on a view, you sometimes need to know which specific text field is being typed into and/or worked with by the user.

Or, let me try to give a practical example: suppose we have a single view with two separate tables. One for hotels and another table for restaurants. Both tables pull data off some object which hosts the data (e.g. maybe a class that works with CoreData?). When "tableView: cellForRowAtIndexPath:" is called on that data source object, the first "tableView" parameter will contain the address of either the hotel table or the restaurant table, and through that, you'll know which data to return back.

于 2013-05-27T03:50:36.277 回答