0

Possible Duplicate:
Use of alloc init instead of new (Objective-C)

Does any of you use +new of the NSObject to alloc & init the object?

Lets say i got an object C derived from Object B which all are from NSObject. To create an instance of Object C

C newInstanceOfC = [C new]; // This will call the alloc & init of class C.

is this any better than

C newInstanceOfC = [C alloc] init];

other than less things to type. What is good practice?

cheers Arun

2
  • You can even do "instance = C.new" though personally I don't care for that form. Commented Oct 11, 2011 at 0:39
  • new is the old way check the link @darvidsOn. It gave me the rite answer. Commented Oct 12, 2011 at 3:51

2 Answers 2

1

alloc] init] is best practice. In particular, objects have different ways to init, including zero, one or more than one parameter. Using new makes an automatic selection of init, but having init visible can help you troubleshoot some nasty bugs that can happen if you initialise a UI element but forget to set the frame, etc.. You'll get compiler warnings about the use of the init method in some circumstances too.

Sign up to request clarification or add additional context in comments.

Comments

0

They are both exactly the same, new is the new way, as that wasn't possible before, but use the one that you like the most.

I usually use new since it is shorter, although in several cases you can't since you usually want to do something like:

[[myObject] alloc] initWith...];

3 Comments

new is the old way. That was the preferred NeXTSTEP procedure. At some point, it was realized that separating the allocation and initialization made certain things easier ([[NSArray alloc] initWithCapacity:]), and now alloc/init is the preferred way in Cocoa. See Chuck's and especially bbum's answer here: stackoverflow.com/questions/3330963/…
@JoshCaswell: Separating alloc and init doesn't make initWithCapacity: any easier as far as I can tell — it would just be newWithCapacity: instead. To the best of my knowledge, what it made easier was primarily memory zones.
@Chuck: Thanks for that note. I admit I've never been quite clear on the reasoning; initWithCapacity: seemed sensible, but apparently was a bad guess.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.