RyJ
RyJ

Reputation: 4025

Populating an NSArray/NSMutableArray, the right way

This is a general question about memory management and best practices when using Cocoa arrays.

Which of the following is "better":

NSArray *pageControllers = [[NSArray alloc] initWithObjects:
    [[Page1 alloc] initWithNibName:@"Page1" bundle:nil],
    [[Page2 alloc] initWithNibName:@"Page2" bundle:nil],
    [[Page3 alloc] initWithNibName:@"Page3" bundle:nil],
                   nil];

...then release NSArray later when not needed anymore...

Or

NSMutableArray *pageControllers = [[NSMutableArray alloc] init];

UIViewController *page1 = [[Page1 alloc] initWithNibName:@"Page1" bundle:nil];
[pageControllers addObject:page1];
[page1 release];

UIViewController *page2 = [[Page2 alloc] initWithNibName:@"Page2" bundle:nil];
[pageControllers addObject:page2];
[page2 release];

UIViewController *page3 = [[Page3 alloc] initWithNibName:@"Page3" bundle:nil];
[pageControllers addObject:page3];
[page3 release];

...then release NSMutableArray later when not needed anymore...

Or is there something else that's even better?

Upvotes: 1

Views: 1515

Answers (1)

Wevah
Wevah

Reputation: 28242

Either way works fine, but keep in mind that you'll be leaking all your page objects in the first example.

Upvotes: 1

Related Questions