在下面的代码中(在ViewDidLoad中),我将一个JSON文件导入iOS项目,然后使用Core Data持久化数据,最后成功执行获取请求。但是,在我删除导入文件并保留数据的代码后,获取请求开始返回(null)
。根据下面的代码,你能解释为什么会这样吗?
id delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegate managedObjectContext];
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"inventorydata" ofType:@"json"];
NSArray* inventoryData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
if(err) NSLog(@"Error %@",[err description]);
NSLog(@"Imported Data: %@", inventoryData);
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:@"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:@"name"];
partsInfo.sku = [obj objectForKey:@"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:@"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:@"partData"];
}];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Supplier"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
self.fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (Supplier *info in self.fetchedObjects) {
NSLog(@"supplierId: %@", info.supplierId);
}
答案 0 :(得分:0)
试试这个。
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:@"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:@"name"];
partsInfo.sku = [obj objectForKey:@"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:@"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:@"partData"];
}];
//Add this code : need to save database.
[delegate saveContext];
// You should add this method in AppDelegate.m
- (void)saveContext{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}