Peter Chen

  • About
  • iOS
  • ML
  • Design

Quick Code Comparison Between Objective C, C++, Java, and Javascript

Feb 22, 2012

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

{code} // 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++

{code} // 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);

#c #java #javascript #objective-c #ios #iphone #code #comparison