不懂内存分析

问题描述:

我已将我的XCode升级到版本3.2.3,以在我的iPhone项目上支持iOS4。我使用静态分析器检查内存管理问题。不懂内存分析

在我的一个例程中,我得到以下问题: 我在向日历添加事件以生成状态后生成用户警报。

这运行良好,但内存分析器不喜欢我如何定义警报。 我看不到编码问题,是吗? (我指定的内存分析提示与 “< < < <”)

- (IBAction) addToCalendar { 
     ... 
    UIAlertView *tmpAlert = [UIAlertView alloc];  <<<<Method returns an Objective-C object with a+1 retain count (owning reference) 

    calData.startDate = iVar.zeitVon; 
    calData.endDate  = iEvent.zeitBis; 
    calData.title  = iVar.title; 
    calData.calendar = myEventStore.defaultCalendarForNewEvents; 

    if ([tmpEventStore saveEvent:tmpEvent span:EKSpanThisEvent error:&tmpSaveError]) { 
     // Show a save success dialog 
     [tmpAlert initWithTitle:@"Success"  <<<<Object released 
         message:@"entry saved" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
    } else { 
     // Show a save error dialog 
     [tmpAlert initWithTitle:@"Error" 
         message:@"entry not saved" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] ; 
    } 
    [tmpAlert show];        <<<<Reference counted object is used after its released 
    [tmpAlert release]; 
} 

感谢

永远不要分离allocinitinit经常改变幕后的对象!尝试

NSString* foo=[NSString alloc]; 
NSLog(@"%p %@", foo, [foo class]); 
foo=[foo initWithString:@"bar"]; 
NSLog(@"%p %@", foo, [foo class]); 

你会看到类似

2010-07-14 01:00:55.359 a.out[17862:903] 0x10010d080 NSPlaceholderString 
2010-07-14 01:00:55.363 a.out[17862:903] 0x100001070 NSCFString 

这表明+[NSString alloc]并没有真正分配任何东西;相反,这项工作本身就是initWithString。我不认为UIAlertView这样做,但你永远不知道。

回顾一下:永不解耦allocinit。我认为静态分析器只是假定每个人都使用[[... alloc] init],这样它就会被你的代码弄糊涂了。分析仪本应警告您不要脱耦allocinit

+0

是的,我现在改变了例程以使2 2gether(alloc&init)和警告消失,谢谢你:) – iFloh 2010-07-14 05:07:16

+1

请向LLVM静态分析器团队提交一个错误报告(关于不要警告decoupled alloc init) :http://clang-analyzer.llvm.org/filing_bugs.html并为社区做一件事! – Yuji 2010-07-14 05:13:41