Alex Rivera | Logout

Want to learn Objective-C but syntax is very confusing

Asked 2010-06-10T00:52:20.703
22

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]; 
Edit
Report

2 Answers

6

Perhaps have a wizz through the wiki page for Objective-C. I just did and found most of your answers.

http://en.wikipedia.org/wiki/Objective-C

I'm from a java background too, on first look objectivec doesn't look too sexy.

It looks like C++ with little bits of syntax on it's face.

What is that dash for and why is followed by void in parenthesis?

minus here denotes an instance method, a plus denotes a class method

I've never seen void in parenthesis in C/C++, Java or C#.

this is the return type

Why don't we have a semicolon after (int) n?

If you don't provide a method body then the syntax is a method declaration - not an implementation.

And lastly what's with the @ signs and what's this implementation equivalent in Java?

@implementation Fraction

@end

in java would probably be

public class Fraction {

}
answered 2010-06-10T01:03:36.090
2

I'm also just getting started with Objective C and I agree about the syntax seeming foreign relative to Java or C++. The best thing I've found is to just read through some example code. I'm sure you can find plenty with a bit of googling. I'm not allowed to post more than one link, but if you google "objective c example code" you should find plenty of code.

If you are just looking for a quick reference to what some of the weird syntax means, this is a pretty good tutorial:

http://cocoadevcentral.com/articles/000082.php

answered 2010-06-10T03:27:06.540

Your Answer