在学习Objective-C和阅读示例代码时,我注意到对象通常是用这种方法创建的:
SomeObject *myObject = [[SomeObject alloc] init];
而不是:
SomeObject *myObject = [SomeObject new];
这是有原因的吗,因为我读到它们是等价的?
在学习Objective-C和阅读示例代码时,我注意到对象通常是用这种方法创建的:
SomeObject *myObject = [[SomeObject alloc] init];
而不是:
SomeObject *myObject = [SomeObject new];
这是有原因的吗,因为我读到它们是等价的?
当前回答
作为旁注,我个人使用[Foo new]如果我想在init中做一些事情,而不使用它的返回值。如果你没有在任何地方使用[[Foo alloc] init]的返回值,那么你会得到一个警告。或多或少,我用[Foo new]来做花瓶。
其他回答
如果new可以帮你完成这个工作,那么它也会让你的代码稍微小一些。如果你在代码的许多不同的地方调用[[SomeClass alloc] init],你将在new的实现中创建一个热点——也就是说,在objc运行时中——这将减少缓存失败的数量。
在我的理解中,如果您需要使用自定义初始化器,请使用[[SomeClass alloc] initCustom]。
如果没有,请使用[SomeClass new]。
+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.
我很晚才提到这个,但我想说的是,这个新在oj - c和Swift的世界里实际上是不安全的。如果你没有创建任何其他初始化式,Swift只会创建一个默认的init方法。在使用自定义初始化项的swift类上调用new将导致崩溃。如果你使用alloc/init,那么编译器会正确地报错init不存在。
作为旁注,我个人使用[Foo new]如果我想在init中做一些事情,而不使用它的返回值。如果你没有在任何地方使用[[Foo alloc] init]的返回值,那么你会得到一个警告。或多或少,我用[Foo new]来做花瓶。
一个简短的回答是:
两者都是一样的。但 'new'只适用于基本的'init'初始化式,而不是 使用其他初始化式(例如initWithString:)。