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:
output = object.methodWithOutput();
output = object.methodWithInputAndOutput(Object input);
output = [object methodWithOutput];
output = [object methodWithInputAndOutput:input];
Obviously, it’s possible to call methods of class, instead of instance:
Object oString = new String();
id oString = [NSString string];
refers any kind of object, so it’s little different from Java counterpart.
Better code is:
String sString = new String();
NSString* sString = [NSString string];
With this style, it’s a little cumbersome write nested calls:
[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:
boolean writeToFile(String path, boolean useAuxiliaryFile)
boolean result = myData.writeToFile("/tmp/log.txt", false);
-(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:
photo.setCaption("Day at the Beach");
output = photo.getCaption();
photo.caption = @"Day at the Beach";
output = photo.caption;
A property should be marked
in declaration and
To create an object, the function
should be called and then an init method should be called:
object = new ComplexObject(1.0f);
object = [[ComplexObject alloc] initWithFloat:1.0f];
When working in an environment without garbage collector, any object created with alloc should be released:
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.