Objective-C for AS3.0 Developers: How to create a new object

In AS3.0 you create a new Object, or instance of a Class, and store it in a reference (or variable) like so:

private var myRef:MyClassName = new MyClassName();
private var myRef:MyClassName = new MyClassNameSubclass();

In Objective-C 2.0, there’re several ways to do this.

Here’s 1 way:

MyClassName *myRef = [[MyClassName alloc] init];

Here’s another:

MyClassName *myRef; //create the reference/variable
myRef = [MyClassName alloc]; //allocate memory of size MyClassName
myRef = [myRef init]; //initiate the MyClassName instance called myRef

And another:

MyClassName *myRef = [MyClassName new];

Why do we have to bother allocating memory manually? AS3.0 developers should be familiar with the concept of Garbage Collection. Objective-C does support GC but not everywhere. For example, the iPhone doesn’t allow it, apparently because of concerns over battery life.

In case you’re wondering, alloc and init are methods inherited from NSObject. Most Objective-C classes in the Foundations Framework inherit from NSObject.

Objective-C 2.0 also allows for dot (.) syntax that Flash/Flex/Actionscript developers are used to.

However, it seems like object instantiation doesn’t fully work with dot syntax. I’m no expert but when I try to write “MyClassName.alloc()” or “MyClassName.alloc” I get errors.
This worked, however:

NSAutoreleasePool * pool = [NSAutoreleasePool alloc]; 
pool = pool.init; 

/*
MyClassName *myRef =  [MyClassName alloc];
myRef = myRef.init;
*/

I’m guessing this means that dot syntax works with Instance methods but not with Class methods.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s