Prabh
Prabh

Reputation: 2474

Difference between the following allocations types?

I have a simple code:

NSMutableArray *arrayCheckList = [[NSMutableArray alloc] init];
[arrayCheckList addObject:[NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2011-03-14 10:25:59 +0000",@"Exercise at least 30mins/day",@"1",nil] forKeys:[NSArray arrayWithObjects:@"date",@"checkListData",@"status",nil]] ];
[arrayCheckList addObject:[NSMutableDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"2011-03-14 10:25:59 +0000",@"Take regular insulin shots",@"1",nil] forKeys:[NSArray arrayWithObjects:@"date",@"checkListData",@"status",nil]]];

Now I want to add a specific index of above array to a dictionary. Below are two way, which one is better and why? What are the specific drawbacks of the latter?

NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary:[arrayCheckList objectAtIndex:1]];

OR

NSDictionary *tempDict = [arrayCheckList objectAtIndex:1];

What would the impact on the latter since I am not doing any alloc/init in it?

Upvotes: 1

Views: 163

Answers (2)

Daniel Bleisteiner
Daniel Bleisteiner

Reputation: 3310

1:

NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary:[arrayCheckList objectAtIndex:1]];

Creates a new immutable dictionary object as a copy of the original one. If you add objects to the mutable dictionary in your arrayCheckList they will not be added to your copied reference.

2:

NSDictionary *tempDict = [arrayCheckList objectAtIndex:1];

This directly pulls the mutable dictionary from your array and not a copy. The following two lines will be equivalent:

[[arrayCheckList objectAtIndex:1] addObject:something];
[tempDict addObject:something];

Upvotes: 1

Caleb
Caleb

Reputation: 125007

The first one potentially copies the dictionary a index 1 of the array. (It should, since you're creating an immutable dictionary but the one in the array is mutable.) The second only gets a reference to the dictionary in the array -- there's no chance of creating a new object.

Upvotes: 0

Related Questions