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];
MyClassName *myRef; //create the reference/variable myRef = [MyClassName alloc]; //allocate memory of size MyClassName myRef = [myRef init]; //initiate the MyClassName instance called myRef
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.
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.