dcp
dcp

Reputation: 55444

objective-c syntax question

I'm trying to learn objective-c, and have a question regarding this method:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
}

According to the documentation, the method name is tableView:cellForRowAtIndexPath:, and it takes 2 parameters, the table view and the index path. It returns a pointer to a UITableViewCell.

So, the (UITableViewCell *) represents the return type, but what I don't understand is why the tv parameter occurs before the cellForRowAtIndexPath method name. It looks to me like what we have here is return type, then param1, then method name, then param2.

I'm really still trying to get an understanding of basic objective-c syntax so any help is appreciated. Thanks.

Upvotes: 1

Views: 595

Answers (2)

Jonathan.
Jonathan.

Reputation: 55544

The method name is tableView:cellForRowAtIndexPath:, all of it, not just cellForRowAtIndexPath:

The - at the beginning means it is an instance method, if it were a class method it would be a +. Eg when you alloc an object,alloc is a class method.

The return type is inside the first brackets. If the method doesn't return anything then the brackets will contain void.

Then comes the first part of the method name, this is between the closing bracket of the return type an the first colon. If the method has no parameters then there is no colon.

Immediately after the colon is the first parameter's type inside brackets.

Immediately after the brackets comes the name of the first parameter.

After a space the method name continues in the same fashion.

enter image description here

Upvotes: 4

PengOne
PengOne

Reputation: 48398

You are quite correct in your description. The basic syntax of a method is

(ReturnObjectType *)someMethodWithInput1:(Input1Type *)input1 
                               andInput2:(Input2Type *)input2
                                andAnInt:(int)input3;

In general, Objective-C doesn't have named parameters, so everything on the left side of a colon is part of the method name. For this example:

- (return_type)instanceMethodWithParameter:(param1_type)param1_varName 
                         andOtherParameter:(param2_type)param2_varName;

The method name is instanceMethodWithParameter:andOtherParameter;. If you use the above to declare the function, e.g. in a header file, then you can change the parameter names in the implementation without a problem. So those are really just for convenience.

Upvotes: 2

Related Questions