0

我有两个数组

  1. retrievedNamesMutableArray
  2. retrievedImagesArray

我保存在核心数据中。虽然保存操作成功,但当我获取数据时,它似乎获取名称或图像,但不能同时获取。我假设我可以将 NSDictionary 存储在 Core Data 中,但似乎无法找到一种方法来做到这一点。

这就是我要保存到 Core Data 的方法。

  -(void)saveToPhoneDatabase
{
   AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
   NSManagedObjectContext *context = [appDelegate managedObjectContext];
   NSManagedObject *newContact;

  /* I assume this can be done but can't figure out proper process.
   NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
  [dictionary setObject:self.retrievedNamesMutableArray forKey:@"NamesArray"];
  [dictionary setObject:self.retrievedImagesArray forKey:@"ImagesArray"];
  */

   for (NSString *object in self.retrievedNamesMutableArray)
   {
    newContact = [NSEntityDescription insertNewObjectForEntityForName:@"AddressBook" inManagedObjectContext:context];
    [newContact setValue:@"GroupOne" forKey:@"groups"];
    [newContact setValue:object forKey:@"firstName"];

   }

   for (UIImage *img in self.retrievedImagesArray)
   {
     newContact = [NSEntityDescription insertNewObjectForEntityForName:@"AddressBook" inManagedObjectContext:context];
     [newContact setValue:img forKey:@"photo"];
     NSLog(@"Saved the photos of Array");
   }

  [context save:nil];
}

这就是我获取的方式。

-(void)fetchFromPhoneDatabase
{
   AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
   NSManagedObjectContext *context = [appDelegate managedObjectContext];
   NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"AddressBook" inManagedObjectContext:context];
   NSFetchRequest *request = [[NSFetchRequest alloc] init];
   [request setEntity:entityDesc];
   NSError *error;
   self.arrayForTable = [context executeFetchRequest:request error:&error];

   NSLog(@"contents from core data = %@",self.arrayForTable);

  [self.tableView reloadData];

 }
4

1 回答 1

1

您的第一个循环创建包含名称但没有图像的对象,您的第二个循环创建包含图像但没有名称的不同对象。

假设(根据您之前的问题)两个数组具有相同的大小,您应该为每个名称/图像只创建一个对象:

for (NSUInteger i = 0; i < [self.reterivedNamesMutableArray count]; i++) {
    NSString *object = self.reterivedNamesMutableArray[i];
    UIImage *img = self.reterivedImagesArray[i];

    newContact = [NSEntityDescription insertNewObjectForEntityForName:@"AddressBook" inManagedObjectContext:context];
    [newContact setValue:@"GroupOne" forKey:@"groups"];
    [newContact setValue:object forKey:@"firstName"];
    [newContact setValue:img forKey:@"photo"];
}
于 2013-09-02T14:01:32.560 回答