PDA

View Full Version : Releasing delegate inside protocol selector




youPhone
Feb 23, 2009, 11:19 AM
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


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


...

- (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.



caveman_uk
Feb 23, 2009, 02:09 PM
What are you attempting to do here?

dejo
Feb 23, 2009, 02:21 PM
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.

youPhone
Feb 23, 2009, 02:22 PM
I guess I didn't make it clear enough. I've now seen this in more than one place.

Take this example:


- (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:
- (void) connectionDidFinishLoading:(NSURLConnection*)theConnection
{
...
[theConnection release];
}

Is this safe?

youPhone
Feb 23, 2009, 02:25 PM
I'm not sure what NSURLConnection does, but UIImagePickerController sets up delegate as @property(nonatomic, assign)

dejo
Feb 23, 2009, 02:56 PM
I guess I didn't make it clear enough. I've now seen this in more than one place.

Take this example:


- (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:
- (void) connectionDidFinishLoading:(NSURLConnection*)theConnection
{
...
[theConnection release];
}

Is this safe?
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: