How to find the Retain count?

大城市里の小女人 提交于 2019-12-12 00:32:17

问题


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

Nsstring *a;
Nsstring *b;

a = [b retain];

what is the retain count of a & b.

a = [b copy];

what is the retain count of a & b.

Thanks in advance.


回答1:


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.
 */

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.


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.




回答2:


NSString doesn't have a retain count that will make sense. But if you're using as a general example, the way to find the retain count for objects that have a normal retain count is:

[a retainCount]


来源:https://stackoverflow.com/questions/7797088/how-to-find-the-retain-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!