Coming from a Java background, I’m still don’t quite understand the semantics of Objective-C methods as opposed to their syntax. Take as an example the following method:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
Easy enough. There is a method named numberOfSectionsInTableView which takes a UITableView as a parameter and returns a NSInteger. Now, how about these methods:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
How should I interpret these methods? I’ve stumbled upon three possible explanations:
1) All three the methods are named tableView and they are overloaded with different parameters. This seems unlikely as people talk about ‘calling the numberOfRowsInSection method’.
2) The methods are named numberOfRowsInSection, heightForRowAtIndexPath and cellForRowAtIndexPath, and the tableView is an artifact due to delegation. In that case, what exactly does the tableView part mean syntactically? If the format of a method is ‘(return)name:parameters, where does tableView fit in?
3) As Objective-C uses message passing, it’s wrong to think about methods. Rather think about passing messages to the object directly. In other words, if the object receives the messages named tableView and numberOfRowsInSection, it knows to execute a certain part of the code. If this is the case, does order matter? Is passing numberOfRowsInSection and tableView the same as passing tableView and numberOfRowsInSection?
The name (or selector, in Objective-C’s parlance) of a method includes all of the parts of the name. For example, look at these three methods, all of which can coexist in the same class:
Note the colon in the name of the version of “foo” that takes a parameter: that’s crucial. The number of parameters that a method takes is part of its name. This is actually strictly defined, because at times in Objective-C you need to refer to the full selector of a method (using the
@selectordirective). See the Selectors section of the Objective-C Programming Language document.Additionally, the order is significant. These two methods are different:
There is no overloading in Objective-C. The compiler won’t dispatch to different methods with the same name but different parameter types.
The leading
tableView:in your examples is simply a common naming convention used for delegates; all delegate selectors will start with a parameter that specifies the object that is delegating functionality.