我正在尝试创建一个字典数组 但是出了点问题我的代码中有一个错误(逻辑),我无法弄清楚它2个小时,(我是iOS开发的新手,所以也许有些经验丰富的人可以快速看到它?)
这是我的代码
已编辑:代码更新
ABAddressBookRef addressBook = ABAddressBookCreate();
CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
//get all contacts names
NSMutableArray* EmailArrayPerPerson = [[NSMutableArray alloc]init];
NSMutableArray* PhoneArrayPerPerson = [[NSMutableArray alloc]init];
for (int i = 0; i < ABAddressBookGetPersonCount(addressBook); i++)
{
NSMutableDictionary *ContactsDetails = [NSMutableDictionary dictionary];
ABRecordRef ref = CFArrayGetValueAtIndex(allPeople, i);
NSString *contact = (__bridge NSString *)(ABRecordCopyCompositeName(ref));
NSLog(@"%@",contact);//contact is good here
ContactsDetails = [NSMutableDictionary dictionary];
[ContactsDetails setObject:contact forKey:@"CName"];
ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
[EmailArrayPerPerson removeAllObjects];
NSLog(@"dictionary is:%@",[ContactsDetails objectForKey:@"CName"]);
for (CFIndex j=0; j < ABMultiValueGetCount(emails); j++)
{
NSString* email = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(emails, j));
[EmailArrayPerPerson addObject:email];
}
[ContactsDetails setObject:EmailArrayPerPerson forKey:@"CEMails"];
ABMultiValueRef multi = ABRecordCopyValue(ref, kABPersonPhoneProperty);
[PhoneArrayPerPerson removeAllObjects];
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++)
{
NSString* phone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(multi, j));
[PhoneArrayPerPerson addObject:phone];
}
[ContactsDetails setObject:PhoneArrayPerPerson forKey:@"CPhones"];
NSLog(@"dictionary is:%@",ContactsDetails);
[Contacts addObject:ContactsDetails];
[Contacts insertObject:ContactsDetails atIndex:i];
NSLog(@"%@",Contacts);
}
NSLog(@"%d",[Contacts count]);
联系人是我的mutableArray,但是当我打印它时 它始终具有所有索引中最后一个字典的值。
当我在每次迭代中打印字典时,我得到了正确的值。 请试一试帮我弄清楚那里有什么问题。
我做了所有答案的混合,现在部分工作,我得到了不同的名字,但邮件和手机仍然是相同的
答案 0 :(得分:2)
您只需创建一个字典,然后在每次迭代中修改它。您的最终结果包含相同的字典N次,而不是最后一个字典的N个副本。
你这样做,基本上是:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
NSMutableArray *dictionaries = [NSMutableArray array];
for (NSInteger i = 0; i < 10; i++) {
dict[@"something"] = @(i);
[dictionaries addObject:dict]; // adding the same dictionary you added last time
}
你想这样做:
NSMutableArray *dictionaries = [NSMutableArray array];
for (NSInteger i = 0; i < 10; i++) {
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"something"] = @(i);
[dictionaries addObject:dict]; // adding the newly created dictionary
}
旁注...不要用大写字母命名变量。在Objective-C中,大写标识符用于类名。这在技术上并不是错误的,但它违背了该语言的标准编码约定,这使得代码更难以为其他开发人员阅读。
答案 1 :(得分:1)
将这行代码放在for循环中
NSMutableDictionary *ContactsDetails = [NSMutableDictionary dictionary];
答案 2 :(得分:1)
尝试替换每个“删除对象调用”,例如
[ContactsDetails removeAllObjects];
[EmailArrayPerPerson removeAllObjects];
重新实例化,即
ContactDetails = [NSMutableDictionary dictionary];
EmailArrayPerPerson = [[NSMutableArray alloc]init];
因为您实际上是在重复地在数组的每个插槽中放置相同的对象。您需要为每次迭代创建新对象。