[英]How to save and retrieve two arrays in Core Data in iOS6
我有兩個數組
retrievedNamesMutableArray
retrievedImagesArray
我保存在核心數據中。 盡管保存操作成功,但是當我獲取數據時,似乎只獲取名稱或圖像,而不是兩者。 我假設我可以在核心數據中存儲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];
}
您的第一個循環創建包含名稱但不包含圖像的對象,而您的第二個循環創建包含圖像但不包含名稱的不同對象。
假設(根據您先前的問題)兩個數組的大小相同,則您應該為每個名稱/圖像僅創建一個對象:
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"];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.