Snaking
Snaking

Reputation: 61

retain count for mutable and immutable object in objective c?

NSArray *arr=[[NSArray alloc]init]; //Am getting all immutable objects allocation that retain count:2  
NSLog(@"dic1:%d",[arr retainCount]); 
[arr retain];
[arr retain];
[arr retain];
[arr release];
 NSLog(@"dic2:%d",[arr retainCount]);


NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];//Am getting all mutable objects allocation that retain count:1  
NSLog(@"dic3:%d",[dic retainCount]);
[dic retain];
[dic retain];
[dic retain];
[dic release];
NSLog(@"dic4:%d",[dic retainCount]);

OUTPUT :dic1:2 dic2:4 dic3:1 dic4:3

what is the diff between mutable objects retain count and immutable objects retain count?pls give me solution...

Upvotes: 4

Views: 261

Answers (2)

hamstergene
hamstergene

Reputation: 24429

If you add the following line

NSLog(@"%p %p %p", [NSArray new], [NSArray new], [NSArray new]);

then you will notice that all pointer values are the same (and also that initial value of dic1 went up by three and now starts with 5). Which means that [[NSArray alloc] init] does not actually allocate anything, but just retains some always-alive singleton and returns it.

Never rely on value of retainCount, because the object may be internally retained by runtime and frameworks. Some objects may not even have retain counter. This also implies that you shouldn't expect that release will predictably cause deallocation.

Upvotes: 6

Infinite Possibilities
Infinite Possibilities

Reputation: 7466

Never use the retainCount method, because it never gives the real values, because the inner implementation of the object may contain retains, so you will have your retains and the system's retains.

Upvotes: 0

Related Questions