2011-03-21 57 views
1

我有一個簡單的代碼:以下分配類型之間的區別?

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

現在我想上面陣列的具體指標添加到字典中。下面是兩種方式,哪一種更好,爲什麼?後者的具體缺點是什麼?

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

OR

NSDictionary *tempDict = [arrayCheckList objectAtIndex:1]; 

什麼會在後者的影響,因爲我不是在做任何分配/初始化?

回答

1

1:

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

創建一個新的不可變的字典對象作爲原始一個的副本。如果您將對象添加到arrayCheckList中的可變字典中,它們將不會被添加到您的複製參考中。

2:

NSDictionary *tempDict = [arrayCheckList objectAtIndex:1]; 

這直接拉動與陣列易變的字典,而不是一個副本。以下兩行將相當於:

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

第一個潛在的複製字典索引1的數組。 (它應該,因爲你正在創建一個不可變的字典,但是數組中的一個是可變的)。第二個只獲得對數組中字典的引用 - 沒有創建新對象的機會。