我正在嘗試關注本教程: http://www.raywenderlich.com/12170/core-data-tutorial-how-to-preloadimport-existing-data-updated 在本教程中,將演示如何構建用於創建sqlite並從json導入數據的腳本。 我有寫:將JSON導入到核心數據中
static NSManagedObjectModel *managedObjectModel()
{
static NSManagedObjectModel *model = nil;
if (model != nil) {
return model;
}
NSString *path = @"AppChecker";
path = [path stringByDeletingPathExtension];
NSURL *modelURL = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"mom"]];
model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
return model;
}
static NSManagedObjectContext *managedObjectContext()
{
static NSManagedObjectContext *context = nil;
if (context != nil) {
return context;
}
@autoreleasepool {
context = [[NSManagedObjectContext alloc] init];
NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel()];
[context setPersistentStoreCoordinator:coordinator];
NSString *STORE_TYPE = NSSQLiteStoreType;
NSString *path = [[NSProcessInfo processInfo] arguments][0];
path = [path stringByDeletingPathExtension];
NSURL *url = [NSURL fileURLWithPath:[path stringByAppendingPathExtension:@"sqlite"]];
NSError *error;
NSPersistentStore *newStore = [coordinator addPersistentStoreWithType:STORE_TYPE configuration:nil URL:url options:nil error:&error];
if (newStore == nil) {
NSLog(@"Store Configuration Failure %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
}
}
return context;
}
int main(int argc, const char * argv[])
{
@autoreleasepool {
// Create the managed object context
NSManagedObjectContext *context = managedObjectContext();
// Custom code here...
// Save the managed object context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
exit(1);
}
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:@"brands" ofType:@"json"];
NSArray* Brands = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"Imported Brands: %@", Brands);
NSString* dataPath2 = [[NSBundle mainBundle] pathForResource:@"products" ofType:@"json"];
NSArray* Products = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath2]
options:kNilOptions
error:&err];
NSLog(@"Imported Products: %@", Products);
}
return 0;
}
的問題是,它創建.sqlite數據庫(和結構是確定),但是沒有數據!
我的數據庫是這樣:
這是我的品牌,例如JSON:
[{
"id":"1",
"name":"TestBrand",
"description":"",
"website":"",
"email":"",
"address":"",
"phone":"",
"from_country_list":"CZ",
"created_at":"2013-11-24 11:51:17.363473",
"updated_at":"2013-11-24 11:51:17.363473"
}]
爲什麼數據不.sqlite進口任何幫助/提示D b ? 非常感謝。
看來你只是通過教程的一半。 JSON數據放入Core Data存儲區的部分在代碼中完全缺失。在這個教程中是'[Banks enumerateObjectsUsingBlock:..'東西。 –