2010-07-13 71 views
1

这是关于使用Cocoa数组时的内存管理和最佳实践的一般问题。填充NSArray/NSMutableArray,正确的方法

下列哪项是 “更好”:

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... 

或者

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... 

或者是有别的,甚至更好?

回答

1

无论哪种方式都能正常工作,但请记住,在第一个示例中,您将泄漏所有页面对象。

+0

谢谢。那么我会继续第二个例子。 – RyJ 2010-07-13 21:58:14

+0

那么,如果你记得自动释放页面或者将它们的指针存储到一个变量中,并且在创建数组之后调用'release',那么第一个示例将不会泄漏。一般来说,对于简单的,非动态的东西,我会去不可变的路线,但它确实无关紧要。 – Wevah 2010-07-14 02:36:57