Ranjeet Sajwan
Ranjeet Sajwan

Reputation: 1921

retain count in iphone

I have used [anArray retainCount] to get the retain count of array..(i know this should not be used but i am using just for learning retain concept)

Following is my code.


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

i think it should be opposite but....

Upvotes: 1

Views: 654

Answers (3)

David Gelhar
David Gelhar

Reputation: 27900

Please do yourself a favor and don't look at retainCount trying to learn how the memory management rules work. Instead refer to the friendly Apple Memory Management Guide.

In your examples:

 NSArray  *anArray =[[NSArray alloc]init];

You have allocated "anArray" (by calling alloc), so you are responsible for calling release.

anArray=[str componentsSeparatedByString:@","];

Now, you have obtained a new object (leaking the original, as seand said). This time, you do not own the object (because componentsSeparatedByString does not have alloc or copy in its name), so you must not release it.

Don't worry about what the retainCount is; tend to your own knitting and release objects that you should and don't release objects you don't own.

Upvotes: 7

seand
seand

Reputation: 5296

This line... anArray=[str componentsSeparatedByString:@","];

You squished the original assignment of 'anArray' (thus creating a leak). In real life, you'd want to [anArray release] first. That's why the retain count went back to 1.

Upvotes: 5

Kevin Sylvestre
Kevin Sylvestre

Reputation: 38092

The documentation states that the retain count is unlikely to provide any useful information. It is NOT a good way to learn about retain and release concepts.

Upvotes: 1

Related Questions