如何将NSArray中的多个对象添加到NSDictionary的一个键中

时间:2016-03-03 18:19:53

标签: ios objective-c nsarray nsdictionary

我有一个带有一些键/值的Object。之后,它被添加到一个数组中。

ContactAlphaB *contact = [ContactAlphaB contactWithFirstName:friendList.firstName lastName:friendList.lastName username:friendList.username country:friendList.country];
[_mucontacts addObject:contact];

每个联系人都有国家/地区差异。我想创建一个NSDictionary,密钥为country,值为此数组中的联系人_mucontacts

示例:内部_mucontacts我有5个联系人:

country of contact1 is Unites State.
country of contact2 is England.
country of contact3 is England.
country of contact4 is Unites State.
country of contact5 is Unites State.

如何创建格式为NSDictionary的内容:

{
    Unites State =     (
        "contact1",
        "contact4”,
        "contact5”
    );
    England =     (
        "contact2”,
        "contact3”
    );
}

3 个答案:

答案 0 :(得分:0)

我不确定我是否完全理解为什么你需要使用国家作为关键字从你的项目中制作字典,但是我假设它,所以你可以轻松地根据国家/地区获取联系人列表。如果是这种情况,您可以跳过将联系人放入字典中,只需使用谓词来过滤现有的对象数组,如下所示:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.country ==[c] England"];
NSArray *filteredArray = [yourArray filteredArrayUsingPredicate:predicate];

在此示例中,SELF表示您的对象类,而国家/地区是您尝试过滤的属性。您也可以轻松地传入NSString而不是将“英格兰”硬编码到谓词中。

答案 1 :(得分:0)

您可以在字典中包含数组值:

NSDictionary * dict = @{ "United States" : @[ "contact1", "contact4", "contact5" ] };

NSMutableDictionary * dict = [ NSMutableDictionary dictionary ] ;
[ dict 
    setValue:@[ "contact1", "contact4", "contact5" ]
      forKey:@"United States" ] ;

按键查找返回一个数组:

NSArray * contactsInUS = dict[@"United States"] ;

答案 2 :(得分:0)

NSDictionary的元素可以是NSArrays

// Create our indexed list of contacts (by country)
NSMutableDictionary *indexedContacts = [[NSMutableDictionary alloc] init];
// Iterate through the contacts
for (ContactAlphaB *contact in _mucontacts) {
    // Get the current list of contacts for the current contact's country
    NSMutableArray *contactsByCountry = [indexedContacts objectForKey:contact.country];
    // If the list doesn't exist for that country yet, create it
    if (!contactsByCountry) {
      contactsByCountry = [[NSMutableArray alloc] init];
      [indexedContacts setObject:contactsByCountry forKey:contact.country];
    }
    // Add the contact to the country list
    [contactsByCountry addObject:contact];
{

// Get list of contacts for England
NSArray *englishContacts = [indexedContacts objectForKey:@"England"];
for (ContactAlphaB *contact in englishContacts) {
  NSLog(@"%@", contact.username);
}