为什么在Objective-C中alloc和init被单独调用? [英] Why are alloc and init called separately in Objective-C?
问题描述
注意:我对Objective-C比较陌生,并且来自Java和PHP。
Note: I'm relatively new to Objective-C and am coming from Java and PHP.
有人可以向我解释为什么我总是先分配和然后初始化一个实例?
Could someone explain to me why I always have to first allocate and then initialize an instance?
无法在init方法中这样做:
Couldn't this be done in the init methods like this:
+ (MyClass*)init {
MyClass *instance = [MyClass alloc];
[instance setFoo:@"bla"];
return instance;
}
+ (MyClass*)initWithString:(NSString*)text {
MyClass *instance = [MyClass init];
[instance setFoo:text];
return instance;
}
...
这只是一个从旧的C天或者有没有我看不到的东西?
Is this just a relict from the old C days or is there something that I'm not seeing?
我知道这不是一个问题,因为我可以总是调用alloc和init,但因为它是一个有点乏味我想至少知道为什么我这样做。
I know this isn't a problem as I could as well always call alloc and init, but since it's a bit tedious I'd like to at least know why I'm doing it.
我喜欢语言的表达性,但这是我的想要完全理解为了思考Objective-C的方式。
I'm liking the expressiveness of the language so far, but this is something that I want to fully understand in order to think the Objective-C way.
谢谢!
推荐答案
+ new结束向类发送一个+ alloc消息,并向-init消息发送从+ alloc返回的任何内容。
+new ends up sending an +alloc message to the class and an -init message to whatever comes back from +alloc.
NeXT离开Stepstone使用+新消息(这是一个Smalltalk想法)的惯例是,早期,他们遇到了他们想要能够多次初始化同一个对象的情况。
The reason that NeXT departed from Stepstone's convention of using the +new message (which was a Smalltalk idea) is that early on, they encountered situations where they wanted to be able to initialize the same object more than once.
这篇关于为什么在Objective-C中alloc和init被单独调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!