我试着写数据与 JSON 到达我 CoreData。当应用程序启动时第一次,我想要获取 JSON 数据,然后将其写入到 CoreData 和在 TableViewCell 中显示它。
但我找不到的方式写入 CoreData JSON。
import CoreData
class TableViewCell: UITableViewCell {
@IBOutlet weak var authorLabel: UILabel!
var context: NSManagedObjectContext? {
get {
let appDel = UIApplication.sharedApplication().delegate as! AppDelegate
let _context = appDel.managedObjectContext
return _context
}
}
var author:AuthorList? {
didSet{
self.setupAuthor()
}
}
func setupAuthor(){
var error: NSError?
let request = NSFetchRequest(entityName: "AuthorList")
let results = self.context!.executeFetchRequest(request, error: &error) as! [Article]
if let _error = error {
println("\(_error.localizedDescription)")
}
self.authorLabel.text = author!.authorName
}
}
这样做的目的-C,但是我没有 Swift
准备去为你的代码。尽管如此,我会贴如何我做到objective-c 带和你可以"转换"到 Swift
。我会认为你的配置你core data内容。
在我 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