From AS3 to Objective-C

Some days after my article about what is happening to Flash developers, I have started to learn Objective-C and I already like it!
In this post, I will try to compare ActionScript 3 to Objecitive-C. I’m really new to Objective-C so if you find any errors in what I say, please add a comment to correct me.

According to Wikipedia : Objective-C is a reflective, object-oriented programming language that adds Smalltalk-style messaging to the C programming language. Today, it is used primarily on Apple’s Mac OS X and iOS. Objective-C is the primary language used for Apple’s Cocoa API.

Objective-C syntax looks like this :

- (id) initWithFrame:(CGRect)frame withText:(NSString *) text {
 
    self = [super initWithFrame:frame];
    if (self) {
        myText = [[NSString alloc] initWithString:text];
    }
    return self;
}

Dammit! What is that!? This funny syntaxe comes from Smalltalk programming language, and I find it has been simplified. Hmm, don’t run away! Objective-C is a beautiful programming language, and finally it’s syntax is easily readable.
However Objective-C has strong concepts, I recommend to learn a bit on C or Java (heir of Smalltalk too) before starting Objective-C. Personally, I’m not very familiar with these programming languages, but I learned them and it was easier to learn Objective-C thanks to their knowledge.

Ok, so now let’s start!

Memory : First of all, in Objective-C (with the last Xcode version) there is a Garbage Collector that you can activate or not! I recommend to do not activate it at first, you should know how manage memory. There are lots of keywords which reference to memory manager : alloc, dealloc, release, retain, and there are also pointers. Memory handling in Objective-C is really unique : it uses a counter to determine the number of instances of an object and when released. The object’s counter is called the retain count. Each object have one. For example if an object is used 3 times, its retain count is 3.
alloc add 1 to the retain count and release remove 1 to the retain count. If the retain count is equal to 0, dealloc method is automatically called and it killed the object. Don’t call the dealloc method yourself!

Keyword differences in AS3 some primitives keyword are :

true; false; null; this;

And in Objective-C :

YES; NO; nil; self;

Variables : Objective-C is based on C, variable declarations are identical.

//AS3 :
var myBoolean:Boolean = true;
var myInteger:int = 4;
//Objective-C :
BOOL myBoolean = YES;
int myInteger = 4;

In Objective-C there are no keywords like var and const, the type is specified before the variable.

Object declarations :

//AS3
var myObject:Object = new Object();
//Objective-C
NSObject *myObject = [[NSObject alloc] init];

In Objective-C most of the objects use NS prefix, it comes from NeXtStep. Objective-C was developed by NeXt (company that Steve Jobs founded after Apple).
You may have noticed the “*” character, yes there are pointers in Objective-C. Pointers are a special data type that points to a location in memory. When a variable is typed to a pointer, accessing that variable will redirect you to the value stored at the pointer’s memory address. More informations on Pointers. That’s mean myObject is a pointer that points to a NSObject instance somewhere in memory.
The keyword “alloc” means that you allocate memory for the object. Then the “init” is the constructor, that’s equivalent to “()”;

Methods and constructors :

//AS3
namespace function outputText():void {
    trace("Hello World");
}
//Objective-C
- (void) outputText {
   NSLog(@"Hello World");
}

Hey, it wasn’t to hard! “namespace” keyword in AS3 syntax can be replaced by public, private or protected. In Objective-C all object’s methods are public! All object’s methods start with a “-“, if we want to use a Class’ function (so a static function) we use a “+”.
If you want to use parameters :

public function paramText(newText:String):void {
   var myText:String = newText;
}
- (void) paramText:(NSSTring *)newText {
   NSString *myText = [[NSString alloc] initWithString:newText];
}

In Objective-C there isn’t default value in function’s parameters : no null, no “”… so if your function signature is :

public function paramText(newText:String = ""):void

You have to write two functions in Objective-C and call the good one :

- (void) paramText
- (void) paramText:(NSString *)newText

There is no name conflicted, because it isn’t the same signature! One is “paramText”, and the other one”paramText:”. It isn’t obvious at first… We calls this function :

paramText();
paramText(newText);
[self paramText];
[self paramText:newText];

A function with two params :

paramText(myText, 4);
public function paramText(myText:String, myNumber:uint);
[self paramText:newText withNumber:4];
- (void) paramText:(NSSTring *)newText withNumber:(uint)myNumber;

If signature name is decently named, it is really friendly to read the function!

Constructors : like for functions, you can have several constructors and call the good one.

NSMutableArray *tab = [[NSMutableArray alloc] init];
// OR :
NSMutableArray *tab = [[NSMutableArray alloc] initWithCapacity:4];

Note that in Objective-C, NSArray like NSString… are static. That means after their initialization, their value can’t change! That’s why some of them have a mutable class : NSMutableArray, NSMutableString… For example : NSMutableString extends NSString, and add a new method : “appendString:”.

Classes : Objective-C extends C (all C code is compatible with Objective-C), so it has the same structure, two files : header (.h) and implementation (.m).

A header is called an interface in Objective-C, it defines inheritance, properties and method signature. It looks like that :

#import 
 
@interface MyObject : NSObject {
 
    NSString *text;
}
 
@property (nonatomic, retain) NSString *text;
 
- (void) paramText;
 
@end

MyObject extends NSObject. I’ve defined one propertie : text. By default, it is protected. You can change this by adding (@public, @protected, @private keywords) :

@interface MyObject : NSObject {
    @public
      NSString *text;
 
    @private
      NSString *text2;
}
@end

Then the @property keyword generates getter/setter, you must precize them like I did if it is an object. But you change its options. In my example : when programm compiles it add automaticaly :

- (NSString *) text {
    return text;
}
 
- (void) setUserName:(NSString *)text_ {
    [text_ retain];
    [text release];
    text = text_;
}

If you don’t precize nonatomic, it’s atomic. Quickly : atomic is use for multi-threading it gives more security on variable accessor, whereas nonatomic doesn’t; nonatomic is faster. Better explanation here and there.
Note, even if you don’t define method in your header file you can create method in your implementation file. They will be hidden from outside (no autocompletion) like if they were private, but they are not! It can be useful if have to many functions and just would like to emphasize some of them.

Moreover adding @property allow object properties to be use like in AS3 with a “.” :

myView = new MyView(rect, myObject.myText);
 myView = [[MyView alloc] initWithFrame:rect withText:myObject.myText];

A simpler exemple of using @property :

@property BOOL myBoolean;

Now the implementation :

#import "MyObject.h"
 
@implementation MyObject
 
@synthesize text;
 
- (id) init {
 
    self = [super init];
 
    if (self) {
 
        text = [[NSString alloc] initWithString:@"my text"];
    }
 
    return self;
}
 
- (void) paramText {
    text = @"my new text";
}
 
- (void) dealloc {
 
    [text release];
 
    [super dealloc];
}
 
@end

The @synthesize refers to the @property. You must use to enable getter/setter. It is really useful :

@synthesize property1, property2, property3;

Like in AS3 we call the parent method thanks to super keyword.
In the init function, we return an id type. Objective-C is a dynamical language, you can use an object even if you don’t know its type thanks to the keyword id which is an object identifier. id is a pointer to an object.
Keyword dealloc is the descrutor, you must release your variables before calling [super dealloc];

In Objective-C like AS3 there are no multiple inheritance, no operator overloading and no templates (there are in CPP). However we can use several interfaces like in AS3 :

public class Bird extends Object implements IAnimals, IWings
@interface Bird : NSObject <IAnimals, IWings>

MVC : Objective-C is based on the MVC pattern.
When a new project start in Xcode, 2 files are created : AppDelegate.h and AppDelegate.m it is like your Application’s Main. Then there are 3 useful classes : NSObject that you already know for your Model, UIView comes from UIKit (#import ) for your View, and finally UIViewController from UIKit too for your Controller. When a new file is created from one of this class, there are already useful methods like : applicationWillResignActive, viewDidLoad, drawRect…. This will be explain in an other tutorial.

To conclude, Objective-C is an awesome programming language, very powerful (not just the language to use if you want to develop on Mac & iOS). This first approach couldn’t explain all about it, there are still lots of things to learn… in a next tutorial 😉

2 thoughts on “From AS3 to Objective-C

Leave a Reply

Your email address will not be published. Required fields are marked *