2013-02-20 85 views
0

以這樣的方式作爲我有個要求,類似對象添加到陣列中,我已創建新的字典。從新詞典修改內容還修改父詞典數據

NSMutableDictionary* existingStepDict = [[[arrayForSteps objectAtIndex:0] mutableCopy] autorelease]; 
[arrayForSteps addObject:existingStepDict]; 
[existingStepDict release]; 

現在,這裏所發生的是,後來當我改變在字典中的任何一個東西,另外一個也得到更新。我需要這些字典獨立行事。

對於我在字典中,其代碼是這樣的深拷貝去了。

NSMutableDictionary* existingStepDict = [[[arrayForSteps objectAtIndex:0] mutableCopy] autorelease]; 

    NSMutableDictionary* destination = [NSMutableDictionary dictionaryWithCapacity:0]; 

    NSDictionary *deepCopy = [[NSDictionary alloc] initWithDictionary:existingStepDict copyItems: YES]; 
    if (deepCopy) { 
     [destination addEntriesFromDictionary: deepCopy]; 
     [deepCopy release]; 
    } 
    //add Properties array to Steps Dictionary 
    [arrayForSteps addObject:destination]; 

但是,這也沒有反映出差異。我知道我在這裏犯了一些小錯誤。 但是,有人能幫我得到我的結果嗎?

非常感謝!

+0

修改我以前的答案,包括另一種選擇 – tkanzakic 2013-02-20 08:12:07

回答

2

這裏有一個簡單的方法來使用NSCoding(系列化)協議的 deepcopy的一個NSDictionary鄰的NSArray。

- (id) deepCopy:(id)mutableObject 
{ 
    NSData *buffer = [NSKeyedArchiver archivedDataWithRootObject:mutableObject]; 
    return [NSKeyedUnarchiver unarchiveObjectWithData: buffer]; 
} 

通過這種方式,您可以複製任何對象以及它在單個步驟中包含的所有對象。

+0

好的,這個工作很完美。非常感謝! – mayuur 2013-02-20 08:13:54

1

當我需要一個NSDictionary的可變深拷貝我創建這個方法的分類:

- (NSMutableDictionary *)mutableDeepCopy 
{ 
    NSMutableDictionary *returnDict = [[NSMutableDictionary alloc] initWithCapacity:[self count]]; 
    NSArray *keys = [self allKeys]; 

    for (id key in keys) { 
     id oneValue = [self valueForKey:key]; 
     id oneCopy = nil; 
     if ([oneValue respondsToSelector:@selector(mutableDeepCopy)]) { 
      oneCopy = [oneValue mutableDeepCopy]; 
     } else if ([oneValue respondsToSelector:@selector(mutableCopy)]) { 
      oneCopy = [oneValue mutableCopy]; 
     } 
     if (oneCopy == nil) { 
      oneCopy = [oneValue copy]; 
     } 

     [returnDict setValue:oneCopy forKey:key]; 
    } 

    return returnDict; 
} 

編輯 和搜索,我發現這個網站,我沒有測試

NSMutableDictionary *mutableCopy = (NSMutableDictionary *)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFDictionaryRef)originalDictionary, kCFPropertyListMutableContainers); 
+0

感謝您的幫助!但我試過'mutableDeepCopy'選項,它沒有解決。但是,馬爾瓦吉奧的答案完美無缺! – mayuur 2013-02-20 08:15:01