标题可能令人困惑,道歉。也许有人可以告诉我一个更合适的标题。
我的.json
文件结构如下。
"sections": [{
"title": "Locations",
"key": "location"
}],
"contacts": [{
"title": "Social Worker",
"name": "Mrs X",
"office": "xxxxxxxx",
"location": "Lisburn",
"department": "xxxxxxxx",
"telephone": "xxx xxxxxxxx"
},...
解析时,我创建一个名为array
的{{1}}。然后,我可以像这样contactsArray
创建AEContact
个对象:
array
在 for (NSDictionary *contactDic in [contactsArray valueForKey:@"contacts"]) {
// Create AEContact objects
_contact = [[AEContact alloc] initWithDictionary:contactDic];
[contacts addObject:_contact];
}
self.contacts = [contacts copy];
self.contacts
中,array
属性的value
是我感兴趣的内容。我需要创建单独的contact.location
相关{ {1}}基于arrays
属性的对象,然后将这些对象映射到AEContact
location
location
key
这是我到目前为止所尝试的:
contactArray
输出是:
dictionary
当NSMutableDictionary *locationsDic = [NSMutableDictionary new];
// Loop through contacts
for (int i = 0; i < self.contacts.count; i++) {
// Sort by location
if ([self.contacts[i] valueForKey:@"location"] == [[[contactsArray valueForKey:@"contacts"] objectAtIndex:i] valueForKey:@"location"]) {
[locationsDic setValue:self.contacts[i] forKey:[[[contactsArray valueForKey:@"contacts"] objectAtIndex:i] valueForKey:@"location"]];
}
}
对象具有相同的{
Ballynahinch = "<AEContact: 0x15dda1fc0>";
Bangor = "<AEContact: 0x15dda2210>";
Lisburn = "<AEContact: 0x15dda1c70>";
...
}
时,它会将其设置为字典中的另一个键/值并覆盖前一个条目。我需要做的是这样的事情:
AEContact
我不确定输出是否应该/看起来像上面的预览,我只能假设我还没有实现我的目标。如何在location
中创建相关的{
Lisburn = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
Bangor = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
}
对象,并将其映射到AEContact
中的array
密钥?感谢。
答案 0 :(得分:2)
标题(以及问题描述)有点难以理解,但我认为您正在尝试通过其位置参数索引(AEContact)对象数组。
我们可以通过一些更严格的命名以及在处理输入时使用find-or-create模式来澄清这一点。
NSDictionary *jsonResult = // the dictionary you begin with
NSArray *contactParams = jsonResult[@"contacts"];
NSMutableDictionary *contactsByLocation = [@{} mutableCopy];
for (NSDictionary *contactParam in contactParams) {
NSString *location = contactParam[@"location"];
// here's the important part: find the array of aecontacts in our indexed result, or
// create it if we don't find it
NSMutableArray *aeContacts = contactsByLocation[location];
if (!aeContacts) {
aeContacts = [@[] mutableCopy];
contactsByLocation[location] = aeContacts;
}
AEContact *aeContact = [[AEContact alloc] initWithDictionary:contactParam];
[aeContacts addObject:aeContact];
}
contactsByLocation
将是我认为您正在寻找的内容。