Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain this Objective-C method declaration syntax

Tags:

objective-c

I'm working through an iPhone development book* without really knowing Objective C. For the most part I'm able to follow what's going on, but there are a few method declarations like the one below that I'm having a bit of trouble parsing. For example:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
  return [self.controllers count]; //controllers is an instance variable of type NSArray in this class
}

It looks this is a method called numberOfRowsInSection, and it returns an NSInteger, and takes an NSInteger as a parameter which is locally called 'section'. But I don't understand all the references to tableView, or why this takes a parameter when it is not used within the method. Can somebody clarify this? Thanks.

*p. 258, Beginning iPhone 3 Development, by Mark and LaMarche, published by Apress

Update: I was able to find another SO thread that goes into a bit more detail: Method Syntax in Objective C

like image 606
Doug R Avatar asked May 26 '10 02:05

Doug R


People also ask

How do you declare method in Objective-C?

An Objective-C method declaration includes the parameters as part of its name, using colons, like this: - (void)someMethodWithValue:(SomeType)value; As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.

What does colon mean in Objective-C?

And again, the colons are just separators to indicate that a parameter is coming. So there you go – now you can read an Objective-C method declaration that takes multiple parameters and returns a value, wacky syntax and all.


1 Answers

This is a method called:

tableView:numberOfRowsInSection:

It takes two parameters:

  • a UITableView*
  • a NSInteger

The method also takes an implicit self parameter , which is the instance it is called with. As dreamlax notes, it also takes an implicit _cmd, which is the method that currently gets invoked.

As Mark says, it is completely common to not use certain parameters if you are conforming to a certain interface.

like image 117
Georg Fritzsche Avatar answered Oct 11 '22 09:10

Georg Fritzsche