Creating a singleton with allocWithZone:

BNRItemStore is singleton, and I was confused by why super allocWithZone: needs to be called instead of the plain old super alloc . And then override alloc instead of allocWithZone .

 #import "BNRItemStore.h" @implementation BNRItemStore +(BNRItemStore *)sharedStore { static BNRItemStore *sharedStore = nil; if (!sharedStore) sharedStore = [[super allocWithZone: nil] init]; return sharedStore; } +(id)allocWithZone:(NSZone *)zone { return [self sharedStore]; } @end 
+6
source share
2 answers

[super alloc] will call allocWithZone: which you redefined to do something else. To actually implement the implementation of the superclass allocWithZone: (what you need there) rather than the overridden version, you must explicitly send allocWithZone:

The super keyword represents the same object as self ; it simply tells the method dispatch mechanism to start looking for the appropriate method in the superclass, not the current class.

Thus, [super alloc] will go to the superclass and get there an implementation that looks something like this:

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

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

+10
source

From Apple documentation :

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

+3
source

Source: https://habr.com/ru/post/922893/


All Articles