我是否正确释放了记忆?

时间:2010-10-26 08:52:53

标签: iphone objective-c cocoa-touch memory nsurlconnection

我有以下帮助对象:

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

performLike会做一些NSURLConnection的东西,然后告诉代表它是否成功。

#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];
    }

}

我是否在正确的位置发布了likeHelper?

2 个答案:

答案 0 :(得分:1)

如果performLike:方法是异步的,那么在调用performLikeFinished:方法之前,可能会释放likeHelper。您应该在所有者对象的dealloc:方法或LikeHelperDelegate中的performLikeFinished:实现中释放likeHelper,以防止过早释放它,但如果您这样做,请注意下面的JeremyPs评论!。

如果performLike:方法是同步的,那么你做的是正确的,但你不需要委托来收集结果。

答案 1 :(得分:0)

是的,您的代码符合指南。

如果您的代码不起作用,则问题可能是LikeHelper需要在self内保留-[LikeHelper performLike:]

您也不应该保留LikeHelperDelegate,这可能是导致混淆或错误的另一个原因。