2013-04-14 43 views
0

我有NSMutableDictionary,看起來像這樣:的NSDictionary:找到一個特定的對象,並刪除它

category =  (
      { 
     description =    (
          { 
       id = 1; 
       name = Apple; 
      }, 
          { 
       id = 5; 
       name = Pear; 
      }, 
          { 
       id = 12; 
       name = Orange; 
      } 
     ); 
     id = 2; 
     name = Fruits; 
    }, 
      { 
     description =    (
          { 
       id = 4; 
       name = Milk; 
      }, 
          { 
       id = 7; 
       name = Tea; 
      } 
     ); 
     id = 5; 
     name = Drinks; 
    } 
); 

現在,當用戶在應用程序中執行一個動作,我得到了@「名稱」值的對象,如「Apple」。我想從字典中刪除該對象,但我怎樣才能達到這個對象與

[myDictionary removeObjectForKey:] 

方法?

+0

這聽起來像你真正想要做的是從'description'數組中刪除一個對象,你想要刪除的對象是具有給定名稱的對象。正確? – rmaddy

+0

嗨rmaddy,這是正確的! – marsrover

+0

剝洋蔥。一次一層。 –

回答

2

在高層次上,您需要獲取對「description」數組的引用。然後遍歷數組獲取每個字典。檢查字典以查看它是否具有匹配的「名稱」值。如果是這樣,請從「description」數組中刪除該字典。

NSString *name = ... // the name to find and remove 
NSMutableArray *description = ... // the description array to search 
for (NSUInteger i = 0; i < description.count; i++) { 
    NSDictionary *data = description[i]; 
    if ([data[@"name"] isEqualToString:name]) { 
     [description removeObjectAtIndex:i]; 
     break; 
    } 
} 
+0

當然,他在一個數組裏面的兩個單獨的字典裏有兩個描述數組,它們在他沒有向我們顯示的字典的「類別」元素內。 –

+0

@HotLicks我想,如果他能夠到達「蘋果」對象開始,他應該知道如何獲得適當的「字典」數組的引用。 :) – rmaddy

+0

謝謝,但我似乎無法正確描述數組。關於「蘋果」的價值,我直接拿到了,不需要翻閱字典。 @HotLicks我想我展示了完整的字典。 – marsrover

1

在一個內部數組中刪除的內容:

NSString* someFood = <search argument>; 
NSArray* categories = [myDictionary objectForKey:@"category"]; 
for (NSDictionary* category in categories) { 
    NSArray* descriptions = [category objectForKey:@"description"]; 
    for (int i = descriptions.count-1; i >= 0; i--) { 
     NSDictionary* description = [descriptions objectForIndex:i]; 
     if ([[description objectForKey:@"name"] isEqualToString:someFood]) { 
      [descriptions removeObjectAtIndex:i]; 
     } 
    } 
} 

要刪除整個組(例如,「水果」)從外陣列是簡單的。

+2

僅供參考 - 您不能在'NSArray'上調用'removeObjectAtIndex:'。 – rmaddy

+0

@rmaddy - 啊,真的。該數組必須先被複制到可變區(如果尚未)。錯過了這一點。 (一般來說,如果從JSON解析中接收數組,則數組不會是可變的。而且,要替換該數組,*包含*對象必須是可變的,一直回到根。) –

+0

謝謝,這似乎工作,但(對不起因爲在屁股中存在這樣的痛苦),這並不會從最初的NSDictionary中刪除對象,這是關鍵部分。 – marsrover

相關問題