iOS中使用用内存引用计数来进行管理。(ARC,MRC)
alloc, retain, copy会使内存引用计数立即+1。
当对象使用结束后要对它进行释放,release(立即-1) ,autorelease(未来-1)。
autorelease的对象会把这个对象放置到离它最近的自动释放池里,自动释放池释放的时候才会把自动释放池中的所有对象的内存引用计数-1。
// autorelease
// 创建自动释放池
//第一种
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// autorelease的对象会把这个对象放到离的最近的自动释放池里, 自动释放池释放的时候才会将自动释放池中的所有对象的引用计数- 1
Student *stu1 = [[Student alloc] init];
[stu1 autorelease];
Student * stu2 = [[[Student alloc] init] autorelease];
//release / drain 二选一
[pool release];
//[pool drain];
// 第二种
@autoreleasepool {
Student *stu3 = [[[Student alloc] init] autorelease];
}
// (栈的特性,先进后出)越晚autorelease的对象越早释放
@autoreleasepool {
Car *myCar = [[Car alloc] init];
Student *myStudent = [[Student alloc] init];
[myStudent setCarBmw:myCar];
[myCar release];
//
Car *a = [myStudent bmw];
[myStudent release];
}
Person *p1 = [[Person alloc] initWithName:@"lla"];
//copy必须是返回一个内存引用计数为1的对象
Person *p2 = [p1 copy];
[p2 release];
[p1 release];
当对象被添加到容器里时,内存引用计数+1。
从容器里移除时,内存引用计数-1。