Question on initializing variable

Discussion in 'iPhone/iPad Programming' started by blindjesse, Nov 19, 2009.

  1. macrumors newbie

    Joined:
    Nov 19, 2009
    #1
    I haven't found a good answer to this question in the relevant documents, but this seems to be a rudimentary thing, so I wonder if I'm missing it somewhere.

    Consider this code:

    Code:
    @interface
    
    class Myclass: NSObject{
     SomeClass *someObject;
    }
    
    @property (nonatomic, retain) SomeClass *someObject;
    @end
    
    
    @implementation
    
    @synthesize someObject;
    
    ...
    
    @end
    
    Now consider initializing that string somewhere. Often in code I've seen, the standard way is this:

    Code:
    
    ....
    SomeClass *anObject = [[SomeClass alloc] init];
    self.someObject = anObject;
    [anObject release];
    
    
    My question is, why not just do this?

    Code:
    self.someObject = [[SomeClass alloc] init];
    
    And then release it in the class' dealloc procedure.

    Thanks
     
  2. macrumors 68040

    Joined:
    Apr 22, 2005
    #2
    When you alloc and init SomeClass, its retain count is set to 1. Since the someObject property is defined to also retain the object, doing

    Code:
    self.someObject = [[SomeClass alloc] init]
    
    results in a retain count of 2 for the object that you have just created, one from alloc/init and one from assigning it via the retained property. Therefore if you just release it in the dealloc method of the class, it will still have a retain count of 1 and will cause a memory leak.
     
  3. macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #3
    You could also just access the instance variable directly:

    Code:
    someObject = [[SomeClass alloc] init];
    Since this isn't calling your setter, you will not be sending a retain message to the new object.

    For an object-oriented purist, you tend to avoid accessing your instance variables directly and relying more on your getters and setters. But to simply initialize your object, go ahead and access the variable directly.
     
  4. thread starter macrumors newbie

    Joined:
    Nov 19, 2009
    #4
    Thanks, this makes good sense.
     
  5. macrumors 68040

    Joined:
    Apr 22, 2005
    #5
    Of course technically this is fine to do if it really is the first time someObject is being set, but it's not a good habit to get into since if someObject -had- already been set, this code would also cause a memory leak, unless you manually release its previous value.
     
  6. macrumors 6502

    Joined:
    Oct 31, 2007
    Location:
    San José
    #6
    You're right. Maybe try:

    Code:
    if (someObject == nil)
    {
        someObject = [[SomeClass alloc] init];
    }
    which is also a good way to initialize your instance variables lazily.
     

Share This Page