Why are alloc and init called separately in Object

2019-01-14 12:49发布

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?

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;
}
...

Is this just a relict from the old C days or is there something that I'm not seeing?

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.

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.

Thank you!

7条回答
叛逆
2楼-- · 2019-01-14 13:35

See NSZone.

+alloc is a shortcut cut for +allocWithZone:, which is a mechanism Cocoa provides for optimizing memory allocation.

So you have the option to do something like this:

foo = [[NSString allocWithZone:MyZone] initWithString:@"Foo"];
foo2 = [foo copyWithZone:MyZone];

The idea behind memory zones is that if you have a large number of similar objects that are frequently allocated and deallocated it may more efficient to use a separate memory zone for those objects.

In order for zoning to be effective you'd want to have +allocWithZone: available to every NSObject subclass, hence you need to separate allocation and initialization. You can create and use all the shortcuts you want, like +new, but underneath it all you need an -init method that initializes an object that has already been allocated.

查看更多
登录 后发表回答