如何在iOS6中的Core Data中保存和检索两个数组

时间:2013-09-02 13:50:39

标签: ios core-data nsarray

我有两个数组

  1. retrievedNamesMutableArray
  2. retrievedImagesArray
  3. 我保存在Core Data中。虽然保存操作是成功的,但是当我获取数据时,它似乎可以获取名称或图像,但不能同时获取两者。我假设我可以在Core Data中存储NSDictionary,但似乎无法找到一种方法。

    这就是我要保存到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];
    
     }
    

1 个答案:

答案 0 :(得分: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"];
}