我已经在 Objective-C 中完成了这项工作,但我没有准备好为你准备的 Swift 代码。尽管如此,我将发布我是如何使用 Objective-C 实现的,您可以将其“翻译”成 Swift。我假设你已经配置了你的核心数据。
在我的AppDelegate 中,我在didFinishLaunchingWithOptions 中添加了一个“检查”:
[self seedDataCheck];
在底部,我创建了以下方法:
- (void)seedDataCheck {
// Count what's in the managedObjectContext
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"YourEntity"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSError *error;
NSUInteger itemsInManagedObjectContext = [self.managedObjectContext countForFetchRequest:fetchRequest error:&error];
// If nothing's there, import JSON
if (itemsInManagedObjectContext == 0) {
NSLog(@"AppDelegate.m seedDataCheck: importSeedData called");
[self importSeedData];
} else {
NSLog(@"AppDelegate.m seedDataCheck: No import required");
}
}
然后我创建了一个单独的方法来导入种子数据:
- (void)importSeedData {
NSError *error = nil;
// Ensure a managedObjectContext is instantiated
if (![self.managedObjectContext save:&error]) {
NSLog(@"Error while saving %@", ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown error");
} else {
NSLog(@"self.managedObjectContext = %@", self.managedObjectContext);
}
// Create dataPath and put items in an NSArray. Nothing is saved, just exists in memory.
NSError *err = nil;
NSString *dataPath = [[NSBundle mainBundle] pathForResource:@"yourJSONData" ofType:@"json"];
NSLog(@"%@",dataPath);
NSArray *yourArrayOfJSONStuff = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
NSLog(@"AppDelegate.m importSeedData: There are %lu items in the array", (unsigned long)stretches.count);
// Take the array of stuff you just created and dump it in the managedObjectContext
[yourArrayOfJSONStuff enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSManagedObject *yourManagedObject = [NSEntityDescription insertNewObjectForEntityForName:@"YourManagedObject"
inManagedObjectContext:self.managedObjectContext];
// Link keys from NSArray * yourArrayOfJSONStuff to NSManagedObjects
yourManagedObject.attribute1 = [obj objectForKey:@"yourAttribute"];
yourManagedObject.attribute2 = [obj objectForKey:@"yourAttribute2"];
// blah blah blah
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
}];
NSLog(@"AppDelegate.m importSeedData: Data imported");
}
我不确定您从哪里获取 JSON,但如果它是静态的(例如电子表格),您可能会发现此站点有助于获取数据以便转储到 JSON 文件中。
http://shancarter.github.io/mr-data-converter/
为了让数据显示在UITableViewCell 中,您可能需要设置UITableViewController 并配置原型单元格以显示来自managedObjectContext 的数据。这是一条相当“行之有效”的道路,因此我将指导您看一下本教程:
http://www.raywenderlich.com/85578/first-core-data-app-using-swift