</pre><pre>
//alloc 开辟内存空间,并且将对象的引用计数由0变1.
Person *per1 = [[Person alloc] init]; //0 - 1
//retainCount 用来获取当前对象的引用计数
NSLog(@"%lu", [per1 retainCount]);
//retain 将对象的引用计数加一
Person *per2 = [per1 retain]; //1 - 2
NSLog(@"%lu", [per2 retainCount]);
[per2 retain]; //2 - 3
[per1 retain]; //3 - 4
NSLog(@"%lu", [per1 retainCount]);
NSLog(@"%lu", [per2 retainCount]);
//release 将对象的引用计数(立即)- 1
[per2 release]; //4 - 3
NSLog(@"%lu", [per2 retainCount]);
[per2 release]; //3 - 2
NSLog(@"%lu", [per2 retainCount]);
[per2 release]; //2 - 1
NSLog(@"%lu", [per2 retainCount]);
[per2 release]; //1 - 0
//过度释放
//现象:当写完和内存引用计数 - 1有关的操作后,程序立即crash
//原因:空间被系统回收后,不能再做和引用计数-1有关的操作,否则立即crash,
//解决方案:删除
// [per2 release];
//当引用计数为0时, 系统会自动回收内存, 我们只管理引用计数
per2 = nil;
per1 = nil;
NSLog(@"%lu", [per2 retainCount]);
//野指针异常
//现象:可能会崩溃,也可能不会崩溃,写到某一行代码时 突然崩溃,(没有写任何引用计数相关的代码)
//产生原因:该对象的空间已经被系统回收,不能访问没有所有权的对象
//解决方案:空间被系统收回后.禁止访问
//错误实例:解决方案:per2 = nil; per1 = nil;
NSLog(@"%lu", [per2 retainCount]);
NSLog(@"%lu", [per2 retainCount]);
NSLog(@"%lu", [per2 retainCount]);
NSLog(@"%lu", [per2 retainCount]);
NSLog(@"%lu", [per2 retainCount]);
}
//内存管理基本原则:
//如果你对一个对象alloc, retain, copy 之后,你就拥有了该对象的所有权,你就必须把它进行release 或者 autorelease.
//========原始========
/*
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Person *per = [[Person alloc] init];//0 - 1
NSLog(@"%lu", [per retainCount]);
//autorelease会将声明为autorelease的对象放入离他最近的自动释放池中,当释放池销毁时,会向池中每一个对象发送一个release消息
[per autorelease];
NSLog(@"%lu", [per retainCount]);
[pool release];
*/
//==========更改=======
@autoreleasepool {
Person *per1 = [[Person alloc] init]; //0 - 1
NSLog(@"%lu", [per1 retainCount]);
[per1 retain]; //1 - 2
//autorelease 会将声明为autorelease的对象放入离它最近的自动释放池中,当自动释放池销毁时,会向池中的每一个对象发送一个release消息 (autorelease 只和释放池有关)
@autoreleasepool {
//释放两次
[per1 autorelease];//2 - 1
[per1 autorelease];//1 - 0
}
NSLog(@"test");
}
//面试题一
@autoreleasepool {
for (long i = 0; i < 100000000; i++) {
@autoreleasepool {
Person *per = [[Person alloc] init];
[per autorelease];
}
}
}
//面试题二
//常量区内存系统管理
//内存泄漏
//涉及三个区(栈区 堆区 常量区)
@autoreleasepool {
NSString *per = [[NSString alloc] init]; //0 - 1
[per retain]; //1 - 2
[per retain]; //2 - 3
per = @"aa";
[per release]; //3 - 2
[per rele7;ase]; //2 - 1
[per release]; //1 - 0
}