Proper way to re-use property?

Discussion in 'iOS Programming' started by shawnl, Sep 19, 2008.

  1. shawnl macrumors newbie

    Joined:
    Sep 16, 2008
    #1
    I have a UIImage property which I need to be able to change the UIImage on the fly.

    Currently I do this like so...

    if (activeImage != nil)
    {
    [activeImage release];
    activeImage = nil;
    }

    activeImage = image;

    The problem I have noticed is as soon as I call the release it shows FREEID(id) in the debugger popup where it used to show UIImage *... so I am thinking that this is not the correct way to release the old resources before filling the new ones... suggestions are appreciated!
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    If that is the entirety of the method why not just synthesize the accessors? That way you can guarantee it's correct.

    Otherwise iirc this is the "correct" way:

    Code:
    - (void) setImage:(UIImage *) theImage
    {
    UIImage *temp;
    if (theImage != image) // This avoids a retain/release cycle if we are trying to set the same image as currently is in use.
    {
      temp = image; // I have assumed the property is called image
      image = [theImage retain]; // We can message nil objects so this should be fine
      [temp release];
    }
    }
    
     
  3. Nutter macrumors 6502

    Joined:
    Mar 31, 2005
    Location:
    London, England
    #3
    There's no need for a temporary variable if you're checking that the objects aren't identical.
     
  4. Sbrocket macrumors 65816

    Sbrocket

    Joined:
    Jun 3, 2007
    Location:
    /dev/null
    #4
    As Nutter mentioned there, the temp var isn't necessary.

    Code:
    - (void) setImage:(UIImage *) theImage {
    	if (theImage != image) {
    		[image release];
    		image = [theImage retain];
    	}
    }
    
     
  5. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #5
    I believe that's what Nutter said above...
     
  6. Sbrocket macrumors 65816

    Sbrocket

    Joined:
    Jun 3, 2007
    Location:
    /dev/null
    #6
    Yes, it is what Nutter said, so I simply posted the change in case someone not quite sure what he meant came across the thread. Is that ok with you? :rolleyes:
     

Share This Page