How to replace the standard / standard memory allocator with my own allocator for all Objective-C classes (not only for my own classes)?
This is not my first need, rather, I'm just curious. At the moment, I have found a solution that seems to work, but it is very unsafe.
@interface NSObject(Allocator) + (instancetype)allocWithZone:(_NSZone*)zone; @end @implementation NSObject(Allocator) + (instancetype)allocWithZone:(_NSZone*)zone { (void)zone; size_t sizeToAlloc = class_getInstanceSize([self class]); void* allocatedMemory = getSharedObjCAllocator().alloc(sizeToAlloc); memset(allocatedMemory, 0, sizeToAlloc); id resultObject = objc_constructInstance([self class], allocatedMemory); return resultObject; } - (void)dealloc { objc_destructInstance(self); if (getSharedObjCAllocator().validatePointer(self, false)) { getSharedObjCAllocator().free(self); } else { ::free(self); } } @end
source share