1

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

1 回答 1

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];
于 2013-09-01T07:03:54.490 回答