如何将@NSManaged对象类中的变量初始化为JSON值?

时间:2018-06-11 16:47:53

标签: swift core-data swifty-json

我想初始化'Item'类中的变量,就像变量'Item2'类

一样

这是'Item'类: -

{
  "name": "my-app",
  "version": "0.0.0",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^5.2.0",
    "@angular/cdk": "^5.2.4",
    "@angular/common": "^5.2.0",
    "@angular/compiler": "^5.2.0",
    "@angular/core": "^5.2.0",
    "@angular/forms": "^5.2.0",
    "@angular/http": "^5.2.0",
    "@angular/material": "^5.2.4",
    "@angular/platform-browser": "^5.2.0",
    "@angular/platform-browser-dynamic": "^5.2.0",
    "@angular/router": "^5.2.0",
    "angular-in-memory-web-api": "^0.5.4",
    "core-js": "^2.4.1",
    "angularfire2": "^5.0.0-rc.10",
    "firebase": "^5.0.4",
    "materialize-css": "^0.100.2",
    "rxjs": "^5.5.6",
    "zone.js": "^0.8.19"
  },
  "devDependencies": {
    "@angular/cli": "~1.7.3",
    "@angular/compiler-cli": "^5.2.0",
    "@angular/language-service": "^5.2.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "~6.0.60",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~4.1.0",
    "tslint": "~5.9.1",
    "typescript": "~2.5.3"
  }
}

这是'Item2'类: -

import UIKit
import CoreData
import SwiftyJSON

class Item: NSManagedObject {

    @NSManaged var name = String()
    @NSManaged var symbol = String()
    @NSManaged var checked : Bool = false
    @NSManaged var buyPrice = String()
    @NSManaged var rank = String()

}

1 个答案:

答案 0 :(得分:0)

ManagedObject不是普通对象。它们是一种面向对象的评估数据库的方法。托管对象使用上下文来获取其所有属性。一个托管对象必须有上下文 - 他们根本没有工作。

extension Item {
    static func insert(json:JSON, in context:NSManagedObjectContext) -> Item{
        let newItem = Item.init(entity: Item.entity(), insertInto:context)
        newItem.name       = json["name"].stringValue
        newItem.symbol     = json["symbol"].stringValue
        newItem.buyPrice   = json["price_usd"].stringValue
        newItem.rank       = json["rank"].stringValue
    }
}

注意这个方法的两个方面:1)它不假设它知道上下文 - 这是一个更高级别的工作 - 对于某些应用程序,它只是直接插入到viewContext中,对于其他应用程序是临时背景上下文被建造。 2)它不保存上下文 - 这也不是它的工作 - 可以同时编辑或创建其他对象,它们都应该以事务方式保存。

它将用于例如:

persistentContainer.performBackgroundTask { (context) in
    let newItem = Item.insert(json: json, in: context)
    do {
        try context.save()
    } catch {
        // log to you analytic provider
    }
}

希望这有帮助。