Question

Please solve this.

NSString *S1 = @"abc";
//retain count of s1 ??

NSString *S2 = [S1 copy];
//retain count of s2 and s1 ??

NSString *S3 = [S2 copy];
//retain count of s3 and s2 ??

NSString *S4 = [S3 retain];
//retain count of s4 and s3 ??

NSString *S1 = @"xyz";
//retain count of s1, s2, s3 and s4 ??

Do not suggest retainCount because i believe that does not give exact result.

Was it helpful?

Solution 2

Edited thanks to clarification from @KurtRevis

Assuming ARC is off, of course, you could test this yourself. But you may not understand why you are getting these results. Here is what you should be getting and why.

NSString *S1 = @"abc";
//retain count of s1 ??

S1 is a constant string literal that will never go leave memory as long as your app is running. So retain count is sort of irrelevant.

NSString *S2 = [S1 copy];
//retain count of s2 and s1 ??

S1 is unchanged. S2 is a copy of S1 with retain count of 1, with no autorelease.

NSString *S3 = [S2 copy];
//retain count of s3 and s2 ??

S2 is unchanged at 1 with no autorelease. S3 is a copy of S2 with retain count of 1, with no autorelease.

NSString *S4 = [S3 retain];
//retain count of s4 and s3 ??

S4 and S3 now point to the same object. And that one object now has a retain count of 2, with an autorelease. Once autorelease is triggered, it will have a retain count of 1, and will not be deallocated.

NSString *S1 = @"xyz";
//retain count of s1, s2, s3 and s4 ??

The old object S1 used to point to is unchanged, it's a persistant string in memory. And now S1 points to a new string which is treated the same way as what S1 used to point to.


Or just save yourself some headaches and use ARC :)

OTHER TIPS

Do not suggest retainCount because i believe that does not give exact result.

Correct. retainCount is useless. www.whentouseretaincount.com

You can only usefully reason about retain counts as deltas.


To answer your question, for that code, the retain count is a constant and none of the lines of code actually do much of anything. At the end of that code, S2, S3 and S4 will all have the same value; will all point to the same string (and, obviously, S1 will point to a different string).

This is because of an implementation detail. You are working with a constant string. It is, effectively, a singleton. Thus, there is never a need to copy the string (copy just does return self;) and the retain/release/autorelease methods do absolutely nothing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top