The 'new' Method

Discussion in 'Mac Programming' started by MorphingDragon, Mar 19, 2010.

  1. MorphingDragon macrumors 603

    MorphingDragon

    Joined:
    Mar 27, 2009
    Location:
    The World Inbetween
    #1
    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)
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    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...
     
  3. teek macrumors member

    teek

    Joined:
    Feb 12, 2008
    Location:
    Norway
    #3
    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 :)
     
  4. kainjow Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #4
  5. gnasher729 macrumors P6

    gnasher729

    Joined:
    Nov 25, 2005
    #5
    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.
     
  6. MorphingDragon thread starter macrumors 603

    MorphingDragon

    Joined:
    Mar 27, 2009
    Location:
    The World Inbetween
    #6
    Shhh, I wrote this just before I went to bed.:eek:

    Ahh, now it makes sense.
     
  7. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #7
    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.
     
  8. MorphingDragon thread starter macrumors 603

    MorphingDragon

    Joined:
    Mar 27, 2009
    Location:
    The World Inbetween
    #8
  9. xStep macrumors 68000

    Joined:
    Jan 28, 2003
    Location:
    Less lost in L.A.
    #9

Share This Page