Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

-Alloc [[]Init] vs. New

I'm not sure I'm getting this correctly, but is there a difference between a initializing a receiver with alloc/Init vs. using +(id)new


Where does the class name argument fit into the +(id)new method?


In either case, once a new instance is returned, does that mean that during runtime the instance of the object will be where the command pointer goes next? And then that instance continues to be available during run until deallocated?


What if you want to have more than one instance of the class available during runtime? Is it better just to initialize one, use it, destroy it, and initialize another, etc, in rapid succession, or better to initialize a quantity of instances, if needed during runtime (if possible)?

iMac

Posted on Jun 18, 2012 8:32 AM

Reply
Question marked as Best reply

Posted on Jun 18, 2012 8:35 AM

Create as many instances of a class that you need at the time you need them.


Depends entirely on your requirements.

49 replies

Jun 18, 2012 9:07 AM in response to mark133

There shouldn't be any difference. "[MyClass new]" and "[[MyClass alloc] new]" should be interchangeable. The last time I really tried, I got complaints from either the static analysis and/or leak checker tools when I used "new". I haven't done this test for a long time. I have noticed that in Apple's recent sample code, they are starting to use "new". I hadn't noticed that before. I need to check on this because I think "new" is cleaner and I would prefer to use it if the tools don't complain.


For the record, only autoreleased values get cleaned up. When you do either "alloc, init" or "new", you must release. One alternative is to use a default autorelased initializer. Instead of doing "[[NSMutableArray alloc] init]" and then releasing, you can just do "[NSMutableArray array]". There are similar autoreleased initializers for other classes.

Jun 18, 2012 9:23 AM in response to msuper69

Michael Superczynski wrote:


" When you do either "alloc, init" or "new", you must release."


Unless you are using ARC.

I'm skeptical about ARC. What does it give me? I'm an old timer so I don't have memory allocation issues.


It just rubs me the wrong way to write bad code and let the runtime pick up the pieces for me. That's a bad habit to get into.

-Alloc [[]Init] vs. New

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple ID.