Creating a singleton with allocWithZone:

后端 未结 2 1062
星月不相逢
星月不相逢 2020-12-31 23:49

BNRItemStore is a singleton, and I was confused on why super allocWithZone: must be called instead of plain old super alloc. And then

相关标签:
2条回答
  • 2021-01-01 00:25

    From Apple's documentation:

    This method exists for historical reasons; memory zones are no longer used by Objective-C.

    0 讨论(0)
  • 2021-01-01 00:49

    [super alloc] will call through to allocWithZone:, which you've overridden to do something else. In order to actually get the superclass's implementation of allocWithZone: (which is what you want there) rather than the overridden version, you must send allocWithZone: explicitly.

    The super keyword represents the same object as self; it just tells the method dispatch mechanism to start looking for the corresponding method in the superclass rather than the current class.

    Thus, [super alloc] would go up to the superclass, and get the implementation there, which looks something like:

    + (id) alloc
    {
        return [self allocWithZone:NULL];
    }
    

    Here, self still represents your custom class, and thus, your overridden allocWithZone: is run, which will send your program into an infinite loop.

    0 讨论(0)
提交回复
热议问题