Sunday 8 February 2009

What's with the square brackets (calling methods)

If you look at some objective C source code, you will see lots of square brackets around. Stuff like :

occultImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"glyph%d.gif", occult]];


seems pretty common.

To a C# programmer that just looks weird... and weird it is. 

But it basically is just another way of calling methods. When you see some square brackets, you know you are calling a method on a particular class or object. Just take it as [object method:parameter].

In the above example we are calling a static method called imageNamed on the UIImage class. The parameter we are passing is the result of another call, stringWithFormat on NSString.

In C#, this would be something like :


occultImage.image = UIImage.imageNamed(NSString.stringWithFormat(@"glyph%d.gif", occult));


What gets more confusing is when you call a method with more than one parameter. The second parameter has to be named. Like so :

NSCalendarDate *startDate = [endDate dateByAddingYears:0 months:0 days:-60 hours:0 minutes:0 seconds:0];


This line will call the function dateByAddingYears on the object endDate (which is another NSCalendarDate) object. Now the first parameter to the function is years. But we dont specify this, we just chuck in the value, which is 0 here. The second parameter is months. We have to specify the name of this parameter. and the same with days, hours, minutes and seconds.

So it is [object method:param1 param2name:param2 param3name:param3] 

Clearer now?

Oh yeah, in object C you aren't calling methods on objects, you are passing messages to them.

hmm...



No comments:

Post a Comment