CodeGuy
CodeGuy

Reputation: 28907

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

Upvotes: 1

Views: 710

Answers (3)

Gonzalo
Gonzalo

Reputation: 187

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

Upvotes: 2

Moszi
Moszi

Reputation: 3236

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 .

Upvotes: 1

Nickolay Olshevsky
Nickolay Olshevsky

Reputation: 14160

Do you release controller after all that stuff?

Upvotes: 4

Related Questions