NaveenKumar NaveenKumar - 2 years ago 122
iOS Question

iOS Retain count

What is the retain count of val and arr in the below code snippet ?

NSString *val=@"qaz";

NSMutableArray *arr=[[NSMutableArray alloc]init];

[arr addObject:val];

Considering we're in MRC.

What is the retain count of str1,str2,str3 and str4 ?

NSString *str1=[[NSString alloc]initwithString:@"str"];

NSString * str2=[str1 copy];

NSString * str3=[str1 retain];

NSString * str4=str3;

I am confused with retain count somebody help me with explanation

Answer Source
NSString *val=@"qaz"; // @"qaz" Counting = 1, handled by val

NSMutableArray *arr=[[NSMutableArray alloc]init]; // NSMutableArray Counting = 1, handled by arr

[arr addObject:val];  // nothing changes


NSString *str1=[[NSString alloc]initwithString:@"str"];  // @"str" Counting = 1

NSString * str2=[str1 copy]; // @"str" Counting = 1; the "copy @"str"" Counting = 1 handled by str2    
NSString * str3=[str1 retain]; // @"str" Counting = 2; the "copy @"str"" Counting = 1 

NSString * str4=str3; // nothing changes

Alloc/init, retain: increase Reference Counting.

Copy: create another object with Counting = 1, not increase Counting of copied object

Release: decrease Reference Counting.

In ARC mode, you don't have to call release, just need to set pointer = nil. Object will be release if there is no pointer handles it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download