views:

67

answers:

2

I have the following helper object:

LikeHelper* likeHelper = [[LikeHelper alloc]init];
likeHelper.delegate = self;
[likeHelper performLike:self.messageID];
[likeHelper release];likeHelper=nil;

performLike will do some NSURLConnection stuff and then tell the delegate whether or not it was successful.

#pragma mark LikeHelperDelegate Methods
-(void)performLikeFinished:(BOOL)isSuccessful{
    if (isSuccessful) {
        UIAlertView *alertView;
        alertView = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"The message has been liked" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }
    else {
        UIAlertView *alertView;
        alertView = [[UIAlertView alloc] initWithTitle:@"Error!" message:@"There was a problem liking your message" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
        [alertView release];
    }

}

Am I releasing the likeHelper in the right place?

+1  A: 

If the performLike: method is asynchronous, the likeHelper will propably be released before the performLikeFinished: method is called. You should release the likeHelper in the dealloc: method of the owner object or in the performLikeFinished: implementation in the LikeHelperDelegate to prevent releasing it too soon but if you do that, be aware of JeremyPs comment below!.

If the performLike: method is synchronous, you are doing the right thing but you wouldn't need the delegate to collect the result.

Gerco Dries
it is asynchronous. does that mean i should declare LikeHelper as a member variable so that I can access it from LikeHelperDelegate?
Sheehan Alam
if I release it in my delegate method, I won't need to release it in dealloc() correct?
Sheehan Alam
@Sheehan Alam: Correct but be careful, if you release the object in the delegate method, when the delegate method returns it will be into the context of an object that might have been deallocated.
JeremyP
Correct JeremyP, releasing it in dealloc: is better than releasing it in the delegate method for that reason.
Gerco Dries
@Gerco I am guessing I will have many instances of likeHelper, until dealloc is called. is this bad?
Sheehan Alam
That depends. On a resource constrained platform like the iPhone, all memory is important and should be released ASAP. You could have the LikeHelper retain itself and release again when the delegate call is complete. This way, you can safely call release from within the delegate without risking the LikeHelper being deallocated too soon.
Gerco Dries
A: 

Yes you are, your code is according to the guidelines.

If your code do not work then the problem might be that LikeHelper need to retain self from within -[LikeHelper performLike:].

You should also not retain the LikeHelperDelegate, that might be another cause of confusion or errors.

PeyloW