使用方法预填充核心数据
Posted
技术标签:
【中文标题】使用方法预填充核心数据【英文标题】:Pre Populate Core Data with a method 【发布时间】:2016-12-07 14:37:34 【问题描述】:我为我的 Core Data 子类创建了一个扩展,在这里我实现了一个预填充表的方法,首先我检查表中是否有任何内容,然后我插入了一些值,但是当我执行获取:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'executeFetchRequest:error: <null> is not a valid NSFetchRequest.'
import Foundation
import CoreData
extension SimulationParams
public static func feedSimulationParams(context: NSManagedObjectContext)
let fetchRequest : NSFetchRequest<NSFetchRequestResult>
if #available(ios 10.0, *)
fetchRequest = SimulationParams.fetchRequest()
else
fetchRequest = NSFetchRequest(entityName: "SimulationParams")
let idDescriptor: NSSortDescriptor = NSSortDescriptor(key: "id", ascending: false)
fetchRequest.sortDescriptors = [idDescriptor]
fetchRequest.fetchLimit = 1
var newId = 0;
do
let results = try context.fetch(fetchRequest)
if(results.count == 0)
self.setValue(getId(fetchRequest: fetchRequest, context: context), forKeyPath: "id")
self.setValue(1.5, forKeyPath: "bankFeePercentage")
self.setValue(1, forKeyPath: "consoMaxMonthly")
self.setValue(12, forKeyPath: "consoMinMonthly")
self.setValue(3.5, forKeyPath: "consoRatePercentage")
self.setValue(4, forKeyPath: "fileFeePercentage")
self.setValue(1, forKeyPath: "immoMaxMonthly")
self.setValue(25, forKeyPath: "immoMinMonthly")
self.setValue(2.05, forKeyPath: "immoRatePercentage")
self.setValue(3, forKeyPath: "prepaymentPenaltyPercentage")
self.setValue(1, forKeyPath: "notaryGridId")
do
try context.save()
catch let error as NSError
print ("Error first demande insertion \(error)")
catch
let fetchError = error as NSError
print(fetchError)
【问题讨论】:
不相关,但为什么不self.bankFeePercentage = 1.5
?你知道...forKeyPath
的真正用途吗?
@vadian 我无法使用 self 访问属性。 forKeyPath,是关于数据库的
【参考方案1】:
解决方案:
警告,您必须在 Data Model Inspector 中删除该模块并将其设置为全局命名空间。
你必须在你的代码上这样做:
let fetchRequest : NSFetchRequest<NSFetchRequestResult>
if #available(iOS 10.0, *)
fetchRequest = Params.fetchRequest()
else
fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Params")
//let predicate = NSPredicate(format: "key=%@", key)
//fetchRequest.predicate = predicate
do
let results = try context.fetch(fetchRequest)
if(results.count != 0)
let params = NSEntityDescription.insertNewObject(forEntityName: "Params", into: context) as! Params
params.setValue(value, forKey: "value")
do
try context.save()
catch let error as NSError
print ("Error first demande insertion \(error)")
else if (results.count == 0)
let params = NSEntityDescription.insertNewObject(forEntityName: "Params", into: context) as! Params
params.key = key
params.value = value
context.insert(params)
catch
let fetchError = error as NSError
print(fetchError)
【讨论】:
以上是关于使用方法预填充核心数据的主要内容,如果未能解决你的问题,请参考以下文章
预填充核心数据存储:使用 JSON 属性列表还是 XML 文件?