2011-04-20 53 views
0

我有一個NSMutableDictionary三個鍵/值對。使用字符串訪問字典的值

key1 - person object1 
key2 - person object2 
key3 - person object3

通過比較一個字符串與字典中的鍵,我需要檢索person對象的內容。我怎樣才能做到這一點?請幫幫我。我的代碼是:

NSArray *keys = [persondict allKeys]; 
    id key; 
    for(int i= 0; i<[keys count]; ++i) 
    { key = [keys objectAtIndex:i]; 
    } 
    for(id key in persondict){ 
     if ([key isEqual:agentrefattr]){ 
      //how to get the person object here? 
      [aperson setPhoneNumber:aperson.PhoneNumber]; 
      [aperson setEmailAddress:aperson.EmailAddress]; 
      [aPersonName setGivenName:aPersonName.GivenName]; 
      [aPersonName setSurname:aPersonName.Surname]; 
      [aperson setPersonName:aperson.PersonName]; 

      [self.agentarray insertObject:aperson atIndex:index]; 
      [self.agentnamearray insertObject:aPersonName atIndex:index]; 
      aperson = [agentarray objectAtIndex:index]; 
      aPersonName = [agentnamearray objectAtIndex:index]; 

      NSLog(@"att:%@",agentrefattr); 
      NSLog(@"Email :%@",aperson.EmailAddress); 
      NSLog(@"Phone :%@",aperson.PhoneNumber); 
      NSLog(@"Given Name :%@",aperson.PersonName.GivenName); 
      NSLog(@"SurName :%@",aperson.PersonName.Surname); 

請幫我一些提示。我想訪問人物對象中的屬性GivenName,Surname等。

回答

4

字典中的鍵是唯一的。因此,如果agentrefattr是一個表示鍵的字符串,那麼yuu將只用該鍵在字典中擁有一個對象,因此根本不需要循環。只是這樣做:

aPerson = [personDict objectForKey: agentrefattr]; 
+1

要清楚;原始海報代碼中的()循環都是毫無意義的。 – bbum 2011-04-20 16:12:48

+0

嗨感謝您的回覆。我嘗試過,但最後一個人物體中的數據只能檢索所有鍵。 kes是獨一無二的,但它的價值正在被來自我的XML的最後一個值覆蓋。 – 2011-04-20 20:20:08

+0

我的代碼有錯誤。有了你的建議,它運行得很好,非常感謝你。 – 2011-04-21 00:40:44

0

一個更好的設計是通過使用enumerateobjectsandkeyswithoption:使用塊:^(ID OBJ,ID鍵)