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];
}