在网上看视频学习关于ios对象之间内存管理的时候,接触到了retainCount。
retainCount是用来返回当前对象内存引用的计数器。alloc、new、copy会设置计数器为1,retain使计数器加1,release使计数器减1。
我们来看下面的代码:
main.m文件里:
void test1(Student *stu) {
Book *book = [[Book alloc] initWithPrice:2.5];
stu.book = book;
NSLog(@"book计数器是%zi",[stu.book retainCount]);
[stu.book release];
NSLog(@"book计数器是%zi",[stu.book retainCount]);
}
void test2(Student *stu) {
NSLog(@"book计数器是%zi",[stu.book retainCount]);
[stu.book buybook];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
Student *stu = [[Student alloc] initWithAge:10];
test1(stu);
test2(stu);
[stu release];
}
return 0;
}
运行结果是这样的:
2016-01-24 22:29:01.563 oc5内存管理[501:22465] book计数器是1
2016-01-24 22:29:01.564 oc5内存管理[501:22465] 价格是2.500000的书背销毁
2016-01-24 22:29:01.565 oc5内存管理[501:22465] book计数器是1
2016-01-24 22:29:01.565 oc5内存管理[501:22465] book计数器是1
(lldb)
如果把[stu.book release]这句注释掉,运行结果是这样的:
2016-01-24 22:30:37.770 oc5内存管理[510:23638] book计数器是1
2016-01-24 22:30:37.770 oc5内存管理[510:23638] book计数器是1
2016-01-24 22:30:37.771 oc5内存管理[510:23638] book计数器是1
2016-01-24 22:30:37.771 oc5内存管理[510:23638] 买的书的价格是2.500000
2016-01-24 22:30:37.771 oc5内存管理[510:23638] 年纪是10的学生被销毁
很显然[stu.book release]的确是把book对象销毁掉了,但是retainCount却打印出计数器为1。
我参考了下面2篇文章:
为什么retainCount为1的时候,release之后还是1?内存管理问题
release 与 retainCount
我们不必特地去查询一个对象的计数器,只要保存内存不泄露就可以了。