
A few people were asking me about how Objective C and its syntax stand out. Common questions came up about Objective C’s properties and synthesize, bracket and dot notation, and function and argument naming, and the class naming with 2 or 3 letter prefixes.
Here’s a quick comparison to give a developer that’s new to Objective C a 2 minute run-through of some syntax differences. I recommend going straight to the code below for your favorite language, and then reading the equivalent Objective C code.
And here’s the equivalent PDF with a nicer side-by-side view.
Objective C
// ASVSquare.h
@interface ASVSquare : ASVShape {
@private
int _width;
}
@property (assign) int width;
+ (NSString *)summaryInfo;
- (void)draw;
- (void)drawInRect:(CGRect *)rect
withBackgroundColor:(CGColor *)color;
@end
// ASVSquare.m
@implementation ASVSquare
@synthesize width = _width;
+ (NSString *)summaryInfo { ... }
- (void)draw { ... }
- (void)drawInRect:(CGRect *)rect
withBackgroundColor:(CGColor *)color
{ ... }
@end
// Usage #import "ASVSquare.h" ASVSquare *mySquare = [[ASVSquare alloc] init]; mySquare.width = 5; NSLog(@”%d”, mySquare.width); [mySquare draw]; [mySquare drawInRect:someRect withBackgroundColor:someColor]; NSLog(@”%@”, [ASVSquare summaryInfo]); [mySquare release];
C++
// Square.cpp
namespace Appssavvy;
class Square : public Shape {
private:
int _width;
public:
int getWidth() {
return _width;
}
void setWidth(int newWidth) {
_width = newWidth;
}
void draw() { ... }
void draw(CGRect *rect,
CGColor *backgroundColor)
{ ... }
static MyString * summaryInfo { ... }
}
// Usage using namespace Appssavvy; #include "Square.h" Square *mySquare = new Square(); mySquare->setWidth(5); mySquare->draw(); mySquare->draw(rect, color); cout << Square::summaryInfo() << endl; delete mySquare;
Java
// Hello.java
package Appssavvy;
public class Square extends Shape {
private int _width;
public int getWidth() {
return _width;
}
public void setWidth(int newWidth) {
_width = newWidth;
}
public void draw() { ... }
public void draw(CGRect rect,
CGColor backgrndColor)
{ ... }
public static String summaryInfo()
{ ... }
}
// Usage import Appssavvy.Square; Square square = new Square(); square.setWidth(5); square.draw(); square.draw(someRect, someColor); System.out.println(Square::summaryInfo());
Javascript
// AppssavvySquare.js import Appssavvy.Square; Square square = new Square(); square.setWidth(5); square.draw(); square.draw(someRect, someColor); System.out.println(Square::summaryInfo());
// Usage ASVSquare square = ASVSquare(); square.width = 5; square.draw(); square.drawInRect(someRect, someColor); console.log(ASVSquare_summaryInfo());