PDA

View Full Version : Simple Question on Syntax




-Garry-
Apr 14, 2009, 12:25 AM
Hi, I know this is really basic but I've been working my way through several books I bought - starting off with basic Objective-C and then onto Cocoa and Interface Builder and I have a question on some syntax I don't think I've seen before. I was hoping somebody could explain it.

In an implementation file I understand you have to define the implementation of your own classes as follows:


-(void) print
{
NSLog (@%i/%i, numerator, denominator);
}

@end

The top line is the line I'm interested in. That's the syntax I've been using so far and I understand it.

I'm now seeing the following:

- (int)numberOfRowsInTableView:(NSTableView *)tv
{
return [voiceList count];
}

Again, the top line is the one I'm interested in. I understand it's saying that the method being defined (numberOfRowsInTableView) returns an integer. It's the second bit (NSTableView *)tv that I don't understand.

I believe it has something to do with passing arguments into the method but I don't understand the syntax. Can anyone explain?



eddietr
Apr 14, 2009, 12:41 AM
- (int)numberOfRowsInTableView:(NSTableView *)tv






This indicates that this method take one parameter and returns an int. The parameter is of type NSTableView* and locally we are calling that parameter 'tv'.

So in the method implementation code we can now refer to the parameter as 'tv'.

Some table view could call this method like so:


int a = [someObject numberOfRowsInTableView: self];

// or someone may do something like this:

int a = [someObject numberOfRowsInTableView: someOtherTableView];


If you are familiar with any other programming language, this is exactly the same concept as function or method parameters in other languages. Just the syntax is a bit different. So in C you might see something similar as:


int numberOfRowsInTableView(NSTableView* tv) {...}

// or in python

def numberOfRowsInTableView (tv):



Hope that helps?

-Garry-
Apr 14, 2009, 03:04 AM
Hi Eddie,

That does help, thank you.

What about the asterisk? Is that declaring that we're not actually passing an object in as an argument - we're passing a pointer in instead?

If so, is there any particular reason it's (NSTableView *)tv rather than NSTableView(*tv) or is it just 'one of those things?'

yoavcs
Apr 14, 2009, 03:34 AM
All references to objects in Objective-C are pointers.

Notice you always declare:

NSObject *anObject;

never

NSObject anObject;

as for the "funky" syntax with the parentheses: just the Objective-C way of doing things.

Think of it as a type cast: (NSTableView *)tv : tv is being cast as a pointer to NSTableView. This isn't technically correct but helped me when I was learning the ropes.