为什么在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 消息,并向 +alloc 返回的任何内容发送 -init 消息.
+new ends up sending an +alloc message to the class and an -init message to whatever comes back from +alloc.
NeXT 背离 Stepstone 使用 +new 消息的惯例(这是 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屋!