核心数据中的多次插入
Posted
技术标签:
【中文标题】核心数据中的多次插入【英文标题】:Multiples inserts in core data 【发布时间】:2017-06-21 12:35:28 【问题描述】:我有很多信息要重新填充我的数据库,我就是这样做的:
let notaryFeeGrid = NSEntityDescription.insertNewObject(forEntityName: "NotaryFeeGrid", into: context) as! NotaryFeeGrid
notaryFeeGrid.id = 0
notaryFeeGrid.notaryLoansAmount = 1000
notaryFeeGrid.notaryFeeAmount = 510
context.insert(notaryFeeGrid)
let notaryFeeGrid2 = NSEntityDescription.insertNewObject(forEntityName: "NotaryFeeGrid", into: context) as! NotaryFeeGrid
notaryFeeGrid2.id = 0
notaryFeeGrid2.notaryLoansAmount = 3000
notaryFeeGrid2.notaryFeeAmount = 530
context.insert(notaryFeeGrid2)
let notaryFeeGrid3 = NSEntityDescription.insertNewObject(forEntityName: "NotaryFeeGrid", into: context) as! NotaryFeeGrid
notaryFeeGrid3.id = 0
notaryFeeGrid3.notaryLoansAmount = 5000
notaryFeeGrid3.notaryFeeAmount = 570
context.insert(notaryFeeGrid3)
这是完整代码的一小部分,我怎样才能将其最小化?
【问题讨论】:
为所有重复代码创建一个函数。然后对于每个“插入”,调用你的函数。 @AgRizzo 使用数组之类的东西可以做得更好吗? 【参考方案1】:试试这个......创建一个公证项数组......
更新:
func addNotary(_ context : NSManagedObjectContext,_ notaryArray: Array) -> Bool
for index in 0...notaryArray.count - 1
let notary : Dictionary = notaryArray[index] as! Dictionary
let notaryFeeGrid = NSEntityDescription.insertNewObject(forEntityName: "NotaryFeeGrid", into: context) as! NotaryFeeGrid
notaryFeeGrid.id = notary["id"]
notaryFeeGrid.notaryLoansAmount = notary["notaryLoansAmount"]
notaryFeeGrid.notaryFeeAmount = notary["notaryFeeAmount"]
var error: NSError?
let success = context.save(&error)
if !success
print("Save failed")
【讨论】:
以上是关于核心数据中的多次插入的主要内容,如果未能解决你的问题,请参考以下文章