为什么Xcode 4.2在main.m中使用@autoreleasepool而不是NSAutoreleasePool?

Foo*_*Foo 14 xcode autorelease nsautoreleasepool ios

我注意到在Xcode 4.2中有一种不同的方式来启动main函数:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil,
                                 NSStringFromClass([PlistAppDelegate class]));
    }
}
Run Code Online (Sandbox Code Playgroud)

int main(int argc, char *argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
Run Code Online (Sandbox Code Playgroud)

有人知道这两者之间的区别吗?

Ign*_*ese 14

第一个是使用ARC,它在iOS5及更高版本中实现,为您处理内存管理.

在第二个,您正在管理自己的内存并创建自动释放池来处理主函数内发生的每个自动释放.

因此,在阅读了有关iOS5的Obj-C的新内容之后,看来:

@autoreleasepool {
    //some code
}
Run Code Online (Sandbox Code Playgroud)

与...一样的工作

NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
// some code
[pool release];
Run Code Online (Sandbox Code Playgroud)

区别在于最后一个会在ARC上抛出错误.

编辑:

第一个是否使用ARC.

  • 请注意,@ autoreleasepool是Objective-C中提供的一种新语句,无论ARC如何都可以使用.见[1](http://clang.llvm.org/docs/AutomaticReferenceCounting.html#autoreleasepool)[2](http://stackoverflow.com/questions/7950583/autoreleasepool-without-arc) (19认同)
  • 所以这个答案是错的."第一个使用ARC"它可能没有使用ARC (7认同)
  • `@ autoreleasepool`是现在的方法.从Apple的"过渡到ARC发行说明":_这种语法适用于所有Objective-C模式.它比使用`NSAutoReleasePool`类更有效; 因此鼓励你采用它代替使用`NSAutoReleasePool`._ (6认同)