如何找到保留计数? [英] How to find the Retain count?

查看:139
本文介绍了如何找到保留计数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请向我解释下面的代码行,我很困惑..

Please explain me the below code of lines, I am just confused..,

Nsstring *a;
Nsstring *b;

a = [b retain];

&的保留计数是多少b.

what is the retain count of a & b.

a = [b copy];

&的保留计数是多少b.

what is the retain count of a & b.

谢谢.

推荐答案

从技术上讲,您发布的情况下的保留计数不确定,因为您从未初始化变量.在未初始化的指针上调用retain可能会崩溃.

Technically the retain count in the situation you posted is indeterminate, since you never initialize your variables. Calling retain on an uninitialized pointer will probably crash.

第二,您的情况下的保留计数取决于您如何初始化变量.

Second, the retain count in your situation depends on how you init your variables.

NSString *a;
NSString *b = @"test";

a = [b retain];

/* Both variables reference the same object which has been retained.
   Retain count +1 
 */

NSString *a;
NSString *b = @"test 2";

a = [b copy];

/* `a` has a retain count +1 (a variable returned from a `copy`
   method has a retain count +1). `b` retain count does not change 
   (you haven't called `retain` on `b`, so it's count remains the
   same.
 */

如果您尚未这样做,则应阅读 Apple的内存管理指南.另外,除非您有很好的理由不这样做,否则应使用

If you haven't done so yet, you should read Apple's memory management guidelines. Also, unless you have a very good reason not to, you should be using ARC, which frees you from most of the headaches from manually managing memory.

在另一个答案的注释中,您询问如何确定对象的保留计数.您总是自己跟踪它.其他对象可能会保留并释放您的字符串,但是您不必在意.如果使用alloc创建对象,并在一个对象上调用retain或在一个对象上调用copy,则在完成该对象后,您有责任释放或自动释放该对象.否则,这不是您的责任.对象的绝对保留数不再重要.

In the comments on the other answer, you ask how to determine the retain count for an object. You always keep track of it yourself. Other objects may retain and release your string, but you don't care. If you create and object using alloc, call retain on an object or copy an object, you are responsible for releasing or autoreleasing that object when you are finished with it. Otherwise it isn't your responsibility. The absolute retain count of an object never matters.

这篇关于如何找到保留计数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆