1

I used following link for understand the retain count.
retain count in iphone
As per that question output is :

NSString *str = [[NSString alloc] initWithFormat:@"a,b,c,d"];
NSArray  *anArray =[[NSArray alloc]init];
NSLog(@"Retain count: %i", [anArray retainCount]);
anArray=[str componentsSeparatedByString:@","];
NSLog(@"Retain count: %i", [anArray retainCount]);  

OUTPUT

Retain count: 2
Retain count: 1

When I tried this code in my example :

NSString *str = [[NSString alloc] initWithFormat:@"a,b,c,d"];
NSArray  *anArray=[[NSArray alloc]init];
NSLog(@"Retain count: %i", [anArray retainCount]);
anArray=[str componentsSeparatedByString:@","];
NSLog(@"Retain count: %i", [anArray retainCount]);

Then OUTPUT is

Retain count: 51
Retain count: 1

I can't understand why the retain count of NSArray is 51 and after assigning value in array it becomes 1.

I also read
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html
http://ranga-iphone-developer.blogspot.in/2011/11/what-is-retain-count-or-reference.html
iOS about retainCount
and other tutorial. but I can't understand the value of Retain count: 51.

Pleas Help me.
Thank You.

Community
  • 1
  • 1
Ilesh P
  • 3,940
  • 1
  • 24
  • 49
  • Why give minus. what is wrong? – Ilesh P Nov 28 '13 at 06:40
  • 1
    Read the answers to the questions that you linked. They're the answers to your question too. – Kurt Revis Nov 28 '13 at 06:40
  • @KurtRevis I read that answer but I can't understand 51 it should be 2 or 1. – Ilesh P Nov 28 '13 at 06:43
  • 2
    The absolute retain count of an object is meaningless. See http://whentouseretaincount.com, http://stackoverflow.com/questions/3730804/how-many-times-do-i-release-an-allocated-or-retained-object/3730835#3730835 or many similar related answers. - In this particular case, `[[NSArray alloc]init]` *might return* a shared instance (compare http://stackoverflow.com/a/18652557/1187415) so its retain count depends on how many instances have already been created. – Martin R Nov 28 '13 at 06:46

1 Answers1

4

See WhenToUseRetainCount.com for an explanation on when and why to use retainCount.

The count is 51 due to an implementation detail of empty arrays. It goes to 1 because you are getting the count of a different object.

If using manual-retain-release, then this pattern is a leak:

Foo *foo = [[Foo alloc] init];
foo = [someObject retrieveTheFooness];

The allocated object is leaked.

Use ARC.

Holly
  • 5,270
  • 1
  • 24
  • 27
bbum
  • 162,346
  • 23
  • 271
  • 359