iOS开发之内存管理
void *calloc(size_t nobj, size_t size) :calloc函数为由nobj个长度为size的对象组成的数组分配内存,并返回指向分配内存区域的指针;若无法满足要求,则返回NULL。该空间的初始长度为0字节。void *malloc(size_t size):malloc函数为长度为size的对象分配内存,并返回指向分配区域的指针;若无法满足要求,则返回NULL。该函数不对分配的内存区域进行初始化。void *realloc(void *p, size_t size):realloc函数将p指向的对象的长度修改为size个字节。如果新分配的内存比原内存大,则原内存的内容保持不变,增加的空间不进行初始化。如果新分配的内存比原内存小,则新分配内存单元不被初始化。realloc函数返回指向新分配空间的指针;若无法满足要求,则返回NULL,在这种情况下,原指针指向的单元内容保持不变。void free(void *p):free函数释放p指向的内存空间。当p的值为NULL时,该函数不执行任何操作。p必须指向先前使用动态分配函数malloc、realloc或calloc分配的空间。
- 生成对象
- 持有对象
- 释放对象
- 废弃对象
+ (id) alloc
{
return [self allocWithZone: NSDefaultMallocZone()];
}
+ (id) allocWithZone: (NSZone*)z
{
return NSAllocateObject (self, 0, z);
}
inline id
NSAllocateObject (Class aClass, NSUInteger extraBytes, NSZone *zone)
{
id new;
int size;
size = class_getInstanceSize(aClass) + extraBytes + sizeof(struct obj_layout);
if (zone == 0)
{
zone = NSDefaultMallocZone();
}
new = NSZoneMalloc(zone, size);
if (new != nil)
{
memset (new, 0, size);
new = (id)&((obj)new)[1];
object_setClass(new, aClass);
AADD(aClass, new);
}
return new;
}
size = class_getInstanceSize(aClass) + extraBytes + sizeof(struct obj_layout);
struct obj_layout {
char padding[ALIGN - ((UNP % ALIGN) ? (UNP % ALIGN) : ALIGN)];
NSUInteger retained;
};
typedef struct obj_layout *obj;
new = NSZoneMalloc(zone, size);
memset (new, 0, size);
new = ( id )&((obj)new)[ 1 ]
object_setClass(new, aClass);
AADD(aClass, new);