我正在获取AddressBook的内容,而后者又被复制到一个数组中。现在我想将这个数组保存到CoreData中。我知道如何在CoreData中插入单个值。我是如何遍历数组来做同样的事情?
这是我试过的。
-(void)fetchAddressBook
{
ABAddressBookRef UsersAddressBook = ABAddressBookCreateWithOptions(NULL, NULL);
//contains details for all the contacts
CFArrayRef ContactInfoArray = ABAddressBookCopyArrayOfAllPeople(UsersAddressBook);
//get the total number of count of the users contact
CFIndex numberofPeople = CFArrayGetCount(ContactInfoArray);
//iterate through each record and add the value in the array
for (int i =0; i<numberofPeople; i++) {
ABRecordRef ref = CFArrayGetValueAtIndex(ContactInfoArray, i);
ABMultiValueRef names = (__bridge ABMultiValueRef)((__bridge NSString*)ABRecordCopyValue(ref, kABPersonCompositeNameFormatFirstNameFirst));
NSLog(@"name from address book = %@",names); // works fine
NSString *contactName = (__bridge NSString *)(names);
[self.reterivedNamesMutableArray addObject:contactName];
NSLog(@"array content = %@", [self.reterivedNamesMutableArray lastObject]); //This shows null.
}
}
-(void)saveToDatabase
{
AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
for (NSString *object in self.reterivedNamesMutableArray) // this array holds the name of contacts which i want to insert into CoreData.
{
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"AddressBook" inManagedObjectContext:context];
[newContact setValue:@"GroupOne" forKey:@"groups"];
[newContact setValue:object forKey:@"firstName"];
NSLog(@"Saved the contents of Array"); // this doesn't log.
}
[context save:nil];
}
答案 0 :(得分:2)
(未来读者请注意:此答案指的是问题的第一个版本。 为了解决这个问题,问题中的代码已经多次更新。) 子>
您的代码只创建一个对象newContact
,并且循环会修改
同一个对象一次又一次。
如果你想要多个对象(每个地址一个),
你必须分别创建每个对象:
for (NSString *object in self.reterivedNamesMutableArray)
{
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"AddressBook" inManagedObjectContext:context];
[newContact setValue:@"GroupOne" forKey:@"groups"];
[newContact setValue:object forKey:@"firstName"];
}
[context save:nil];