简体   繁体   中英

Memory Leaks - Objective-C

Can anyone see potential leaks in this code? I'm getting a "100%" leak according to Instruments on the line "NSString *ender = [temp stringFromDate:now];"

        NSDateFormatter* temp = [[NSDateFormatter alloc] init];
        [temp setDateFormat:@"yyyy-MM-dd"];
        NSDate *now = [NSDate date];
        NSString *ender = [temp stringFromDate:now];

        DashboardViewController *controller = [[DashboardViewController alloc] init];
        [controller initWithStartDate:ender andEndDate:ender];
        [controller initAccount:account];

        [self presentModalViewController:controller animated:NO];
        [temp release];

所有这些东西后,您是否释放控制器?

This advice is unrelated to original question, but I think you should rename the initWithStartDate:andEndDate: and initAccount: methods since typically methods with "init" in the name return new instances.

Perhaps create your own -(id)initWithStartDate:endDate:account: and call the designated initializer from within.

Then you would create a new controller instance with

DashboardViewController *controller = [[DashboardViewController alloc] initWithStartDate:ender endDate:ender account:account];

Gonzalo

Since you pass your controller instance to the -presentModalViewController: method, that method will retain your controller. So you can safely release your controller, but you also should release your controller, since the memory management rules state that objects that you alloc+inited are owned by you and must be released.

On the other hand - just a small note - NSDateFormatter is a "heavy" object, cache the instance and reuse it, if it's possible. Probably this is also the reason why Apple deprecated this method. You might call -init on NSDateFormatter from iOS 2.0 till iOS 3.2, but it is deprecated after iOS 3.2 .

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