在学习Objective-C和阅读示例代码时,我注意到对象通常是用这种方法创建的:

SomeObject *myObject = [[SomeObject alloc] init];

而不是:

SomeObject *myObject = [SomeObject new];

这是有原因的吗,因为我读到它们是等价的?


当前回答

很老的问题,但我写了一些例子只是为了好玩-也许你会发现它有用;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

在main函数中这两个语句:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

得到相同的输出:

2013-03-06 16:45:44.125 XMLTest[18370:207]分配。 [18370:207]初始化。

其他回答

通常情况下,你需要传递参数给init,所以你将使用不同的方法,如[[SomeObject alloc] initWithString: @"Foo"]。如果你习惯了这样写,你就会养成这样做的习惯,所以[[SomeObject alloc] init]可能会比[SomeObject new]来得更自然。

这里有一堆原因:http://macresearch.org/difference-between-alloc-init-and-new

精选的有:

new不支持自定义初始化器(比如initWithString) Alloc-init比new更显式

一般的观点似乎是你应该使用任何你觉得舒服的东西。

如果new可以帮你完成这个工作,那么它也会让你的代码稍微小一些。如果你在代码的许多不同的地方调用[[SomeClass alloc] init],你将在new的实现中创建一个热点——也就是说,在objc运行时中——这将减少缓存失败的数量。

在我的理解中,如果您需要使用自定义初始化器,请使用[[SomeClass alloc] initCustom]。

如果没有,请使用[SomeClass new]。

很老的问题,但我写了一些例子只是为了好玩-也许你会发现它有用;)

#import "InitAllocNewTest.h"

@implementation InitAllocNewTest

+(id)alloc{
    NSLog(@"Allocating...");
    return [super alloc];
}

-(id)init{
    NSLog(@"Initializing...");
    return [super init];
}

@end

在main函数中这两个语句:

[[InitAllocNewTest alloc] init];

and

[InitAllocNewTest new];

得到相同的输出:

2013-03-06 16:45:44.125 XMLTest[18370:207]分配。 [18370:207]初始化。

+new is equivalent to +alloc/-init in Apple's NSObject implementation. It is highly unlikely that this will ever change, but depending on your paranoia level, Apple's documentation for +new appears to allow for a change of implementation (and breaking the equivalency) in the future. For this reason, because "explicit is better than implicit" and for historical continuity, the Objective-C community generally avoids +new. You can, however, usually spot the recent Java comers to Objective-C by their dogged use of +new.