Releasing delegate inside protocol selector

Discussion in 'iPhone/iPad Programming' started by youPhone, Feb 23, 2009.

  1. macrumors member

    Joined:
    Sep 8, 2008
    #1
    I have run across some code and I don't think it is a correct approach, but I thought I would ask and see what other thinks.

    Essentially, you have a class (MyClass) and a protocol (<MyClassDelegate>) and a protocol selector

    Code:
    MyClass *myClass = [[MyClass alloc] init];
    [myClass setDelegate:self];
    
    ...

    Code:
    - (void) myClass:(MyClass*)thisMyClass myObject:(id)someObj
    {
    	...
    	...
    	[thisMyClass release];
    }
    It seems to me that dealloc should be called on my instance of MyClass as soon as it is released in the protocol method.

    If there are any other calls after calling the protocol method within MyClass, then the app should crash I would think.
     
  2. Guest

    caveman_uk

    Joined:
    Feb 17, 2003
    Location:
    Hitchin, Herts, UK
    #2
    What are you attempting to do here?
     
  3. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #3
    Based on what myClass is subclassed from, the setDelegate: may be doing a retain, which would possibly cause the later release to not dealloc the instance.
     
  4. thread starter macrumors member

    Joined:
    Sep 8, 2008
    #4
    I guess I didn't make it clear enough. I've now seen this in more than one place.

    Take this example:

    Code:
    - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo 
    { 
    	...
    
    	[[picker parentViewController] dismissModalViewControllerAnimated:YES]; 
    	[picker release];
    }
    Is it safe to release the picker inside its delegate protocol method?


    Here's another example:
    Code:
    - (void) connectionDidFinishLoading:(NSURLConnection*)theConnection
    {
    	...
    	[theConnection release];
    }
    Is this safe?
     
  5. thread starter macrumors member

    Joined:
    Sep 8, 2008
    #5
    I'm not sure what NSURLConnection does, but UIImagePickerController sets up delegate as @property(nonatomic, assign)
     
  6. Moderator

    dejo

    Staff Member

    Joined:
    Sep 2, 2004
    Location:
    The Centennial State
    #6
    Yeah, they're both safe because they are being used in methods that are called when the program is finished dealing with those instances. I.E. didFinishPickingImage: and connectionDidFinishLoading:
     

Share This Page