wil*_*lc2 337 oop objective-c
学习Objective-C并阅读示例代码,我注意到对象通常是使用以下方法创建的:
SomeObject *myObject = [[SomeObject alloc] init];
Run Code Online (Sandbox Code Playgroud)
代替:
SomeObject *myObject = [SomeObject new];
Run Code Online (Sandbox Code Playgroud)
是否有理由这样做,因为我已经读到它们是等同的?
Jer*_*ley 286
这里有很多原因:http://macresearch.org/difference-between-alloc-init-and-new
一些选定的是:
new
不支持自定义初始值设定项(如initWithString
)alloc-init
比...更明确 new
一般意见似乎是你应该使用你喜欢的任何东西.
gui*_*eak 137
很老的问题,但我写了一些只是为了好玩的例子 - 也许你会发现它很有用;)
#import "InitAllocNewTest.h"
@implementation InitAllocNewTest
+(id)alloc{
NSLog(@"Allocating...");
return [super alloc];
}
-(id)init{
NSLog(@"Initializing...");
return [super init];
}
@end
Run Code Online (Sandbox Code Playgroud)
在main函数中都有两个语句:
[[InitAllocNewTest alloc] init];
Run Code Online (Sandbox Code Playgroud)
和
[InitAllocNewTest new];
Run Code Online (Sandbox Code Playgroud)
导致相同的输出:
Run Code Online (Sandbox Code Playgroud)2013-03-06 16:45:44.125 XMLTest[18370:207] Allocating... 2013-03-06 16:45:44.128 XMLTest[18370:207] Initializing...
Bar*_*ark 52
+new
相当于+alloc/-init
Apple的NSObject
实现.这种情况不太可能发生变化,但根据您的偏执程度,Apple的文档+new
似乎允许在未来改变实施(并打破等效性).出于这个原因,因为"显式优于隐式"而且对于历史连续性,Objective-C社区通常会避免+new
.但是,您可以通过他们的顽固使用来发现最近的Java角色到Objective-C +new
.
通常,您需要传递参数init
,因此您将使用不同的方法,例如[[SomeObject alloc] initWithString: @"Foo"]
.如果你习惯于写这篇文章,你会习惯这样做,所以[[SomeObject alloc] init]
可能更自然地来[SomeObject new]
.