开发者

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 th开发者_C百科e 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?


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];


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜