当时Alloc不止一个对象

时间:2014-02-14 13:04:31

标签: ios objective-c memory-management nsobject nsset

我想知道当时如何允许多个对象。我正在寻找类似于NSSet的50个空对象。

这样做的原因是我需要进行大量分配(1.000.000)的密集工作,并且每个基础都需要花费很多时间。 (Alloc方法费时费力。)

2 个答案:

答案 0 :(得分:2)

有一篇关于Cocoa With Love的文章Alternative Objective-C object allocation for large arrays关于分配

答案 1 :(得分:1)

要直接回答您的问题,有两个运行时函数可以让您创建/破坏位于预先分配的内存块中的对象:

/** 
 * Creates an instance of a class at the specific location provided.
 * 
 * @param cls The class that you wish to allocate an instance of.
 * @param bytes The location at which to allocate an instance of \e cls.
 *  Must point to at least \c class_getInstanceSize(cls) bytes of well-aligned,
 *  zero-filled memory.
 */
OBJC_EXPORT id objc_constructInstance(Class cls, void *bytes) 
    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0)
    OBJC_ARC_UNAVAILABLE;

/** 
 * Destroys an instance of a class without freeing memory and removes any
 * associated references this instance might have had.
 */
OBJC_EXPORT void *objc_destructInstance(id obj) 
    __OSX_AVAILABLE_STARTING(__MAC_10_6, __IPHONE_3_0)
    OBJC_ARC_UNAVAILABLE;

完全未经测试的示例用法(必须在@implementation文件中禁用ARC):

+ (void)allocInPlace:(void *)buffer
{
    objc_constructInstance(self, buffer);
}

- (void)dealloc
{
    objc_destructInstance(self);
}

size_t instanceSize = class_getInstanceSize(MyClass.class);

// This may not be enough, since we need to ensure that object instances are 16-byte aligned
void *buffer = calloc(instanceSize, numObjects);

for (size_t i = 0; i < numObjects; i++) {
    // Need to ensure that this is 16-byte aligned
    void *objBuffer = buffer + (instanceSize * i); 
    [mySet addObject:[[MyClass allocInPlace:objBuffer] init]];
}

不再需要时,您需要暂停bufferfree()

然而如果可能的话,您应该只使用C数组结构。我在这里使用的技术与标准的Obj-C实践相反,并且容易出错(例如,如果在所有对象被破坏之前释放缓冲区,那么就会发生坏事)。