I am trying to implement simple Core Data class to store and retrieve different Language strings(array) downloaded from the server. So far I have created created Core Data template in App Delegate, created data model with one Entity "MyArray" and one Attribute "language", and written following sample code to store and retrieve these arrays. Now as both the strings arrays stored in same attribute "language", how I can retrieve Chinese language array?
// Fetch arrays code
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyArray" inManagedObjectContext:context];
[request setEntity:entity];
NSArray *results = [context executeFetchRequest:request error:nil];
for (NSManagedObject *object in results) {
NSArray *a = [object valueForKey:@"language"];
// Use array
}
-(void)storeEnglishStrings {
NSArray *array = [[NSArray alloc] initWithObjects:@"str1",@"str2", @"str3", @"str4", @"str5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:@"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
-(void)storeChineseStrings {
NSArray *array = [[NSArray alloc] initWithObjects:@"串1",@"串2", @"串3", @"串4", @"串5", nil];
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[object setValue:array forKey:@"language"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
Check out the Core Data programming guide. You will need to use an NSFetchRequest with a predicate for the chinese language. You need to make sure you can identify which one is the language of the record you are saving. I do not see the structure of your entity but I do see you are not saving the language. Also, you should reconsider your model. You usually should not need to save an NSArray into core data. You can, but it usually means your model is lacking better design.