Objective-C: [[Class alloc] init] Alternative

John C. Bland II

Reading more in the book I found what makes more sense to me in terms of instantiating a class.

My previous post showed this as the way:

MyClass myClassInstance = [[MyClass alloc] init];

…effectively calling the alloc and init methods on the class then the class instance, respectively.

I see now you can simply do this:

MyClass myClassInstance = [MyClass new];

This makes WAYYY more since coming from ECMA where you’d do:

MyClass myClassInstance = new MyClass(); //java and C#
var myClassInstance:MyClass = new MyClass(); //as3

The author suggests still using the two step approach, alloc/init, so you know you are calling two distinct methods. I will probably use “new” instead because it is more intuitive to me.

On Chapter 4 (Data Types and Expressions) now. More to come.




2 Responses to “Objective-C: [[Class alloc] init] Alternative”

  • Dave M. Says:

    You do realize that there is more to the ‘init’ part of the alloc/init than just init.

    looking at NSArray for instance, you can do several different types of init. initWithObject, initWithObjects, initWithContentsOfFile and more. These can’t be done after the alloc/init part since this is a static array.

    The new is great for just creating the object, but there are typically helpers in Cocoa that do pretty much the same thing. [NSMutableArray array] is an example. It basically does the same thing as ‘new’ using the word ‘array’ instead. There are other classes that do the same thing.

    I’m still not 100% up on memory management in Cocoa, but from what I have read, the words used to create an object tells you whether you need to ‘release’ the object or if it will autorelease later. I don’t remember quite what those are yet, but I’m pretty sure the word ‘new’ is one of those words that signals that the programmer is responsible for releasing the data later. If using [NSArray new] would mean that you still have to release the object later, then the ‘new’ would be fine, otherwise it might get confusing.

  • John C. Bland II Says:

    @Dave M.
    Great info!

    I actually just read about the different uses for init or shall I say the extra init methods usually used. I have a blog post coming up soon about this one.

    I’m still learning so feel free to comment on any of these posts. They are 100% here to improve my learning experience (if I write about it, it sinks in a bit better; if folks comment, it gives me real-world insight, most of the time; lol).

Leave a Reply

  • Get Adobe Flash playerPlugin by wpburn.com wordpress themes