Reputation: 1457
I am fetching the contents of AddressBook which in turn are copied into an array.Now i want to save this array into CoreData.I know how to insert single values in CoreData.How do i loop through an array to do the same?
Here is what i tried.
-(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];
}
Upvotes: 1
Views: 1116
Reputation: 540055
(Note for future readers: This answer refers to the first version of the question. In order to solve the problem, the code in the question has been updated several times.)
Your code creates only a single object newContact
, and the loop modifies
the same object again and again.
If you want multiple objects (one for each address),
you have to create each object separately:
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];
Upvotes: 2