ios关于retainCount的一些疑问

在网上看视频学习关于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
我们不必特地去查询一个对象的计数器,只要保存内存不泄露就可以了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值