0

我已將我的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]; 
} 

感謝

回答

5

永遠不要分離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