【问题标题】:Memory leak while using performSelectorInBackground使用 performSelectorInBackground 时内存泄漏
【发布时间】:2012-05-30 06:28:40
【问题描述】:

我是 iOS 开发的新手。我在运行后台线程时遇到问题。在我的代码中,resetUi 在主 UI 线程上运行,现在我正在启动一个后台线程来获取图像数据并更新我的图像。一切正常,但调用 performSelectorInBackground 时内存泄漏。

请让我知道我哪里做错了。另外请建议在从 URL(dataWithContentsOfURL) 获取时是否有更好的方法来更新我的图像。

[更新]

Instrument 显示 2 个单独的泄漏,一个在 perfromSelectorInBackground,另一个在 UIImage imageWithData。我猜 imageupdate(imageWithData) 出了点大问题

-(void)updateData{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];     

    profileName.text = oAuthTwitter.screen_name;

    if(profilePic.image == nil){
        NSString *urlString = @"https://api.twitter.com/1/users/profile_image/";
        urlString = [urlString stringByAppendingFormat:oAuthTwitter.screen_name];   
        urlString = [urlString stringByAppendingFormat:@"?size=bigger"];            
        profilePic.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]];          
        [activityIndicator stopAnimating];
        [activityIndicator release];
    }   
    [pool drain];   

}   

- (void)resetUi{

    if (oAuthTwitter.oauth_token_authorized) {
        profilePic.hidden = NO;
        profileName.hidden = NO;

        NSLog(@"Resetting to authorised state");
        [self performSelectorInBackground:@selector(updateData) withObject:nil];

    }else{

        NSLog(@"Resetting Twitter UI to non-authorized state.");

    profilePic.hidden = YES;
        profileName.hidden = YES;       

    }

}   

【问题讨论】:

    标签: ios memory-leaks background-process performselector


    【解决方案1】:

    我认为你应该使用

    [pool release];
    

    而不是

    [pool drain];
    

    这是更好的做法。

    你也可以尝试在主线程中释放activityIndi​​cator吗?

    从您提供的代码中,我找不到任何其他泄漏原因。您是否尝试过使用泄漏仪器和静态分析器运行您的代码?

    【讨论】:

    • 是的,我正在使用泄漏仪器运行代码。如果有任何其他替代方法可以从 URL 获取图像,请澄清我。我想这是造成所有麻烦的原因。
    • 您是否更改了我在答案中提到的活动指标?另外关于从 URL 获取图像,您的逻辑看起来不错,我认为这不是您的问题的原因
    • 是的,我已按照您的建议将 activityIndi​​cator 移至主线程。当我从 URL 获取图像(在主线程上运行)时,除了这个程序之外的其余两个地方,即使这样也存在内存问题。
    • 我不确定,但你有没有看过用户 Sam 对this 问题的回答。据我了解,你在问题中提供的代码没有泄漏,除非有苹果您使用的任何方法中的错误。
    • 我尝试了该解决方案的所有可能性。最终,即使这样也没有成功。使用该解决方案时仍然显示 NSData 的泄漏。
    猜你喜欢
    • 2011-01-27
    • 2011-02-23
    • 2021-07-06
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多