Coming from Java background I am guessing this is expected. I would really love to learn Objective-C and start developing Mac apps, but the syntax is just killing me.
For example:
-(void) setNumerator: (int) n
{
numerator = n;
}
What is that dash for and why is followed by void in parenthesis? I’ve never seen void in parenthesis in C/C++, Java or C#. Why don’t we have a semicolon after (int) n? But we do have it here:
-(void) setNumerator: (int) n;
And what’s with this alloc, init, release process?
myFraction = [Fraction alloc];
myFraction = [myFraction init];
[myFraction release];
And why is it [myFraction release]; and not myFraction = [myFraction release]; ?
And lastly what’s with the @ signs and what’s this implementation equivalent in Java?
@implementation Fraction
@end
I am currently reading Programming in Objective C 2.0 and it’s just so frustrating learning this new syntax for someone in Java background.
UPDATE 1: After reading all these answers and Programming in Objective C 2.0 a little further, it’s all starting to make sense now!
UPDATE 2: Thanks for the great tip “support-multilanguage”. We can combine these two statements into one like so:
myFraction = [Fraction alloc];
myFraction = [myFraction init];
Can be reduced to:
myFraction = [[Fraction alloc] init];
The dash
-means “instance level” ( which is the default in Java ). When you see a plus sign+it means class level ( same as usingstaticin Java )The void in parenthesis is the return type see below.
Because that’s the method signature, you can think of it as a interface:
Same situation.
Objective-C having roots in C ( actually this is the real C with objects ) needs a header file ( completely removed in Java ) where you define what the functions/methods your class would have.
The equivalent if such thing would exist in java would be:
allo-init is the equivalent for
newin Java,allocthat’s when you ask for memory for your object,allocrequest memory, andinitcalls theinitmethod, equivalent to the Java class constructor ( btw Ruby does the same behind scenes )There’s no equivalent to release in Java because it is garbage collected, in Objective-C you have to release your object.
BTW, the initialization could also be
myFraction = [[Fraction alloc]init];That’s the class definition as I mentioned earlier.
Here’s a related answer that will help you to get more familiar with the square brackets:
Brief history of the “square brackets” is I remember it.