使用MBProgressHUD进行内存泄漏

时间:2010-12-20 21:44:43

标签: iphone objective-c memory-management

我正在使用MBProgressHUB,找到here代码的变体。

关于我的代码的一些事情:

  • 代码在我的App Delegate
  • 许多其他课程称之为
  • 我正在使用异步NSURLConnection
  • 声明:@property(nonatomic,retain)MBProgressHUD * HUD;
  • :@synthesize HUD;
  • (当然我不会在我的dealloc中发布)

我按如下方式使用它:

- (void)setSearchingMode:(BOOL)isSearching {
    // when network action, toggle network indicator and activity indicator
    if (isSearching) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];

        //HUD.labelText = @"Connecting";
        [HUD show:YES];
    } else {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

        [HUD hide:YES];
        [HUD removeFromSuperview];
        [HUD release];
    }
}

- (void)setSearchingText:(NSString *)whatToSay {
    HUD.labelText = whatToSay;
}

我很确定代码在某处导致了内存管理问题。在我的崩溃日志中,我得到:

  

异常类型:EXC_BAD_ACCESS(SIGBUS)
  例外代码:KERN_PROTECTION_FAILURE位于0x0000000c

     

0 libobjc.A.dylib 0x000027d8 objc_msgSend + 16
  1我的0x00003120 - [MyAppDelegate setSearchingMode:](MyAppDelegate.m:363)
  2我的0x00003458 - [MyAppDelegate connectionDidFinishLoading:](MyAppDelegate.m:341)
  3基础0x00032896 - [NSURLConnection(NSURLConnectionReallyInternal)sendDidFinishLoading] + 62
  4基金会0x00032818 _NSURLConnectionDidFinishLoading + 72

在connectionDidFinishLoading中我打电话:

[self setSearchingMode:NO];

我尝试通过为HUD创建属性访问器来实现它,但是无法绕过“[MBProgressHUD alloc] initWithWindow” - 并且我不想继续分配ivar!

谢谢,如果有人能指出我在这里更好的方向..

1 个答案:

答案 0 :(得分:1)

如果你碰巧得到以下序列:

[self setSearchingMode:YES];
[self setSearchingMode:NO];
[self setSearchingMode:NO];

由于对HUD的悬空引用,该代码将如所描述的那样崩溃。执行[HUD release];后,请在该行后添加HUD = nil;

这不是内存泄漏;这是一个过度释放。或者,更有可能是悬挂参考。

  

(当然我不会发布它   我的dealloc)

为什么不呢?如果你保留它,你最好释放它!