如何正确用我的自定义分配器替换标准/默认内存分配器所有 Objective-C类(不仅适用于我自己的类)?
这不是我的第一需要,更像是我对此感到好奇。现在我最终得到了解决方案,这似乎有效,但它非常不安全:
@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