Jan 19 2010

Objective-C for busy Java Developers 1: Calling methods

Category: java,objective-c,tutorialgiordano scalzo @ 2:34 pm

At last I got a wonderful MacBookPro, so I started to study Objective-C to develop some cool Iphone applications.

Objective-C is a language derived from C, to which it adds some modern features as ObjectOriented or Smalltalk-style messaging.

As far I’m a complete newbie, I’m trying to learn it recalling some well know patterns and scenarios as made in Java , following this good tutorial.

Objective-C has a little strange way to call method, that could be disorienting at first glance:

Java:

object.method;
object.methodWithInput(input);

output = object.methodWithOutput();
output = object.methodWithInputAndOutput(Object input);

Objective-C:

[object method];
[object methodWithInput:input];

output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];

Obviously, it’s possible to call methods of class, instead of instance:

Java:

Object oString = new String();

Objective-C:

id oString = [NSString string];

The

id

refers any kind of object, so it’s little different from Java counterpart.
Better code is:

Java:

String sString = new String();

Objective-C:

NSString* sString = [NSString string];

With this style, it’s a little cumbersome write nested calls:

Java:

calculator.add(numbers.split());

Objective-C:

[calculator add:[numbers split]];

This syntax disencourage the nesting of more than one method.

Some methods take multiple input arguments, Objective-C deals with that allowing split method names:

Java:

boolean writeToFile(String path, boolean useAuxiliaryFile)

boolean result = myData.writeToFile("/tmp/log.txt", false);

Objective-C:

-(BOOL)writeToFile:(NSString *)path withAuxFile:(BOOL)useAuxiliaryFile;

BOOL result = [myData writeToFile:@"/tmp/log.txt" withAuxFile:NO];

Objective-C has properties built in, in Java you need to implement getters and setters:

Java:

photo.setCaption("Day at the Beach");
output = photo.getCaption();

Objective-C:

photo.caption = @"Day at the Beach";
output = photo.caption;

A property should be marked

@property

in declaration and

@synthesize

in implementation.

To create an object, the function

alloc

should be called and then an init method should be called:

Java:

object = new ComplexObject(1.0f);

Objective-C:

object = [[ComplexObject alloc] initWithFloat:1.0f];

When working in an environment without garbage collector, any object created with alloc should be released:

Objective-C:

[object release];

To complete this introductory post, take a look at this ObjectiveC CheatSheet: it contains all the most used constructs needed to start to code for Mac.

Technorati Tags: , ,

Tags: , ,

  • Facebook

    nice post

  • R_o

    good explanation. thank you.