- (NSInteger) tableView: (UITableView *) tableView numberOfRowsInSection: (NSInteger) section
I’m pretty comfortable with obj-c, but I don’t understand this method signature. Specifically why this method has all that extra stuff before the method name, and what it means. Like I get that the - is an instance method, and that the return type is NSInteger
but why is tableView: (UITableView *) tableView in front of the method name?
WHy do some instance methods for the UITableViewDataSource protocol have nothing infront of the name? numberOfSectionsInTableViewis defined differently.
Can someone explain it to me?
Lets break it down into parts:
This means it’s an instance method. The alternative is
+which means class method.This is the return type of the method. In this case it’s
NSInteger.The first component of the selector name (which is, in full,
tableView:numberOfRowsInSection:). The:indicates that a parameter follows.The type of the parameter.
The name of the parameter. This is largely irrelevant in the method signature (except as a hint to the reader as to the purpose), but in the implementation this is the variable that is bound to that parameter.
The next component of the selector name.
The type of the second parameter.
The name of the second parameter.
Note, the only required space in this entire line is the one between
tableViewandnumberOfRowsInSection:. All other spaces can be elided to produceThough the most common format you’ll find looks like this:
Edit: Looks like there’s still some confusion about the latter part of the question. The
tableView:component of the selector is there to provide theUITableView*instance that’s asking the question. All of the methods in theUITableViewDataSourceprotocol provide the sending tableview as an argument. Some of these methods have other arguments, and some don’t. The ones that have additional arguments are all formatted astableView:someOtherThing:(e.g.tableView:numberOfRowsInSection:), but this isn’t required. It could be callednumberOfRowsInTableView:forSection:, ornumberOfRowsInSection:ofTableView:, or evenfoo:bar:, but it’s a stylistic choice that was made by the API developer to preserve a consistent naming scheme that assist both the developer and the person reading the code later. As for the methods that don’t take any other parameters, they look likenumberOfSectionsInTableView:because that’s just a natural name for the method. They can’t be calledtableView:numberOfSectionsbecause that’s an illegal selector (all components after the first must have a parameter associated, and therefore must have a trailing:).