【问题标题】:swift - JSON to CoreDataswift - JSON 到 CoreData
【发布时间】:2015-09-11 04:35:21
【问题描述】:

我尝试将使用 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  
    }
}

【问题讨论】:

    标签: ios json swift core-data


    【解决方案1】:

    我已经在 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

    【讨论】:

      猜你喜欢
      • 2016-10-30
      • 2017-06-28
      • 2015-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      • 2018-02-24
      • 1970-01-01
      相关资源
      最近更新 更多