NaveenKumar
NaveenKumar

Reputation: 650

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

Upvotes: 1

Views: 457

Answers (1)

tuledev
tuledev

Reputation: 10317

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

MRC

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.

Upvotes: 4

Related Questions