【问题标题】:Populating an NSArray/NSMutableArray, the right way以正确的方式填充 NSArray/NSMutableArray
【发布时间】:2010-07-13 21:36:20
【问题描述】:

这是一个关于使用 Cocoa 数组时的内存管理和最佳实践的一般问题。

以下哪个“更好”:

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

或者还有什么更好的?

【问题讨论】:

    标签: objective-c memory-management nsmutablearray nsarray


    【解决方案1】:

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

    【讨论】:

    • 谢谢。然后我将继续第二个示例。
    • 好吧,如果您记得自动释放页面或将它们的指针存储到变量并在创建数组后对它们调用release,那么第一个示例将不会泄漏。一般来说,对于简单的、非动态的事情,我会走不可变的路线,但你用哪种方式真的不重要。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多