Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

MorphingDragon

macrumors 603
Original poster
Mar 27, 2009
5,159
6
The World Inbetween
One thing I dont get about Obj-C. All the people that I know that program in Obj-C recommend against [object new], instead of [[object init] alloc].

Why? I thought any methods/peices of code that automate functions in Obj-C optimise the code in some way. (Like @synthesize etc)
 
That should be
Code:
[[object alloc] init]

As to why no-one uses new, I'm not 100% sure. Obviously quite a lot of classes have initWithX: methods so new wouldn't do the same thing...
 
Isn't [obj new] just syntactic sugar, doing exactly the same as [[obj alloc] init] ? I find it strange that most people don't use the new keyword. But then again why change when you're used to alloc init :)
 
One thing I dont get about Obj-C. All the people that I know that program in Obj-C recommend against [object new], instead of [[object init] alloc].

Why? I thought any methods/peices of code that automate functions in Obj-C optimise the code in some way. (Like @synthesize etc)

Because the "new" method is a pointless addition that only works in the rare case when you can use an init method without parameters. And it complicates the rules for object ownership: When you create an object using alloc or a method name with "create" or "copy" then _you_ own the object. And if you use "new" - one more thing to remember.
 
That should be
Code:
[[object alloc] init]

As to why no-one uses new, I'm not 100% sure. Obviously quite a lot of classes have initWithX: methods so new wouldn't do the same thing...

Shhh, I wrote this just before I went to bed.:eek:

Because the "new" method is a pointless addition that only works in the rare case when you can use an init method without parameters. And it complicates the rules for object ownership: When you create an object using alloc or a method name with "create" or "copy" then _you_ own the object. And if you use "new" - one more thing to remember.

Ahh, now it makes sense.
 
Because the "new" method is a pointless addition that only works in the rare case when you can use an init method without parameters. And it complicates the rules for object ownership: When you create an object using alloc or a method name with "create" or "copy" then _you_ own the object. And if you use "new" - one more thing to remember.

As I understand it, when you create an object with alloc, copy or new, you get a object that is retained and you own it. So I'm confused at what point you are trying to make.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.