简体   繁体   中英

Don't understand memory analysis

I have upgraded my XCode to versio 3.2.3 to support iOS4 on my iphone project. using the static analyser I checked for memory management problems.

In one of my routines I get the following problem: I generate a user alert after adding an event to the calendar to give him a status.

This runs fine, but the memory analyser doesn't like how I defined the alert. I can't see the coding problem, do you? (I indicated the memory analyser hints with "<<<<")

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

thanks

You should never decouple alloc and init . init often changes the object behind the scenes! Try

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

You'll see something like

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

This shows that +[NSString alloc] doesn't really allocate anything; rather, what does the job is initWithString itself. I don't think UIAlertView does this, but you never know.

To recap: never decouple alloc and init . I think the static analyzer just assumes that everyone use [[... alloc] init] , so that it got confused by your code. The analyzer should have warned you not to decouple alloc and init .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM