Monday, December 15, 2008

Objective-C for C++ / Java developers

Here I document the differences between Objective-C and another object oriented language like C++ / Java. The goal is to get someone, who has a fair grasp of object oriented concepts in either C++ or Java or (preferably) both, started with understanding / writing Objective-C code as soon as possible. The goal being effective iPhone Development. If you are reading this without any background, please read my previous post about objective-c "hello world" program structure, and creating a first basic class in objective-c.

This blog entry is a work in progress. I will keep updating this as I learn more about objective-c.

Differences between Objective C and C++ / Java.



















































ConceptC++ / JavaObjective-CDetails
File name extension.h / .c / .cpp / .java.h / .mDeclarations in .h file. Implementation in .m
Declaring a method / messageint add(int x, int y)- (int) add:(int)x with:(int)ytypes are always enclosed in brackets
Calling the method / sending a messageint result = obj.add(10, 12);int result = [obj add:10 with:12];message name and first parameter are same
Nesting method callsint r = obj.add(obj.getX(), obj.getY);int r = [obj add:[obj getX] with:[obj getY]];
FormattingAll printf formats (%s, %d etc)All C formats, and %@%@ prints and object's "description"
Calling methods in parent classsuper.init();[super init];
Refering to myself / current objectthis.add(10, 12);[self add:12 with:12];



Other things
  • Type (id) represents current class. No need to specify name of the class
  • NULL: the keyword "nil" represents a null value.
  • Message passing is nil safe. nil elements do not core dump / throw a NullPointerException. Data members are auto-initialized to nil
  • All method / message binding in Objective-C is dynamic. Classes maintain a list of messages that will be accepted at runtime. All other messages are passed on to parent. This processing happens at run time.
  • For Class level messages, replace the "-" with "+" as the first character of the message declaration and implementation

No comments:

Post a Comment