How to find the Retain count?

2019-08-19 01:40发布

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.

2条回答
做自己的国王
2楼-- · 2019-08-19 02:02

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]
查看更多
Melony?
3楼-- · 2019-08-19 02:07

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.

查看更多
登录 后发表回答