gpt4 book ai didi

ios - swift - JSON 到 CoreData

转载 作者:搜寻专家 更新时间:2023-10-31 22:49:54 26 4
gpt4 key购买 nike

我尝试将使用 JSON 获取的数据写入我的 CoreData。当应用程序首次启动时,我想获取 JSON 数据,然后将其写入 CoreData 并显示在 TableViewCell 中。

但我找不到将 JSON 写入 CoreData 的方法。

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
}
}

最佳答案

我已经在 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 并配置您的原型(prototype)单元格以显示来自您的数据托管对象上下文。这是一条非常“人迹罕至”的道路,所以我将指导您看一下本教程:

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

关于ios - swift - JSON 到 CoreData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035630/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com