Search code examples
objective-cmemory-managementcopyretaincount

please solve here retain count of NSString objects in Objective C


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.


Solution

  • 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 :)