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

Community
  • 1
  • 1
Arun Dev
  • 27
  • 1
  • 6

2 Answers2

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.

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...];
Oscar Gomez
  • 18,436
  • 13
  • 85
  • 118
  • `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: http://stackoverflow.com/questions/3330963/alloc-init-and-new-in-objective-c – jscs Oct 11 '11 at 01:32
  • @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 Oct 11 '11 at 02:55
  • @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. – jscs Oct 11 '11 at 03:23