You own it, you release it

Discussion in 'iOS Programming' started by teguh123, Apr 7, 2011.

  1. macrumors member

    Joined:
    Mar 22, 2011
    #1
    Does that mean that the alloc and release will always be on the same function (with the exception of destructor?)
     
  2. macrumors G4

    Small White Car

    Joined:
    Aug 29, 2006
    Location:
    Washington DC
    #2
    I don't see how anyone could think otherwise!
     
  3. macrumors regular

    Joined:
    Feb 17, 2011
  4. macrumors 601

    vincenz

    Joined:
    Oct 20, 2008
    #4
    I'm just as confused by you by this post :confused:
     
  5. blevins321, Apr 7, 2011
    Last edited by a moderator: Apr 7, 2011

    macrumors 68030

    Joined:
    Dec 24, 2010
    Location:
    Olympia, WA
    #5
    yes. I've never seen the allocator and release in different functions. I always make a separate destructor though.
     
  6. huskerchad, Apr 7, 2011
    Last edited by a moderator: Apr 7, 2011

    macrumors regular

    Joined:
    Jul 17, 2002
    #6
    No, alloc and release do not always occur in the same function. For example, one object creates another object (and stores a pointer to it) at init time...then at dealloc time, releases it. Very common.
     
  7. macrumors 6502

    Savage

    Joined:
    Mar 12, 2008
    Location:
    Long Island, NY
    #7
    Actually, your post is the most confusing post in this thread...
     
  8. macrumors 6502

    seepel

    Joined:
    Dec 22, 2009
    #8
    To elaborate on this, imagine that you have an object of class Car that needs to access another object of class Wheel for Car's entire life span. You would want to create the Wheel when you create the Car, retain it. And then you release the Wheel when dealloc is called on the Car. Here would be init and dealloc for Class Car.

    Code:
    
    @interface Car : NSObject {
        Wheel *wheel_;
    }
    
    @end
    
    
    @implementation Car
    
    - (id)init {
        if((self = [super init])) {
            wheel_ = [[Wheel alloc] init];
        }
        return self;
    }
    
    - (void)dealloc {
        [wheel_ release];
        [super dealloc];
    }
    
    @end
    
    
     
  9. macrumors 68040

    Joined:
    Apr 22, 2005
    #9
    An additional release that could go along with seepel's example would be in the setter method:

    Code:
    - (void)setWheel(Wheel *aWheel) {
          if(aWheel != wheel_) {
             [wheel_ release];
             wheel_ = [aWheel retain];
          }
    }
    
    This is what the compiler generates for you if you synthesize a retained property.
     
  10. thread starter macrumors member

    Joined:
    Mar 22, 2011
    #10
    So with the exception of init and dealloc couple, alloc and release are always on the same function.

    admanimal sample actually illustrate it. Retain is like alloc in a sense of increasing retain count.
     

Share This Page