我正在获取 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];
}