代码之家  ›  专栏  ›  技术社区  ›  RyJ

填充NSArray/NSMutableArray,正确的方法

  •  1
  • RyJ  · 技术社区  · 14 年前

    这是关于使用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...
    

    或者还有更好的吗?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Wevah    14 年前

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