使用字符串访问字典的值

时间:2011-04-20 14:30:36

标签: objective-c cocoa nsmutabledictionary

我有一个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);

请帮我一些提示。我想访问person对象中的属性GivenNameSurname等。

2 个答案:

答案 0 :(得分:4)

字典中的键是唯一的。因此,如果agentrefattr是表示键的字符串,则yuu将只使用该键在字典中有一个对象,因此根本不需要循环。就这样做:

aPerson = [personDict objectForKey: agentrefattr];

答案 1 :(得分:0)

更好的设计是使用enumerateobjectsandkeyswithoption:using block:^(id obj,id key)