0

iPhone プロジェクトで iOS4 をサポートするために、XCode をバージョン 3.2.3 にアップグレードしました。静的アナライザーを使用して、メモリ管理の問題をチェックしました。

私のルーチンの 1 つで、次の問題が発生します。イベントをカレンダーに追加してステータスを表示した後、ユーザー アラートを生成します。

これは正常に実行されますが、メモリ アナライザーはアラートの定義方法を気に入りません。コーディングの問題がわかりませんね。(メモリアナライザーのヒントを「<<<<」で示しました)

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

ありがとう

4

1 に答える 1

4

allocと を切り離してはいけませんinitinit舞台裏でオブジェクトを変更することがよくあります。試す

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が、あなたは決して知りません。

要約すると、 と を分離allocしないでinitください。静的アナライザーは、誰もが を使用していると想定している[[... alloc] init]ため、コードによって混乱したと思います。allocアナライザーは、 と を分離しないように警告しているはずですinit

于 2010-07-14T05:04:50.940 に答える