一对多关系CoreData Swift
Posted
技术标签:
【中文标题】一对多关系CoreData Swift【英文标题】:One to many relationship CoreData Swift 【发布时间】:2015-01-10 15:18:08 【问题描述】:Core Data 在大多数情况下都非常有效。当我点击 name first VC (Items) 并 performSeque to the second VC (Costs) 时,我可以看到 costName 和其他数据。但是当我在第一个 VC 中添加第二个名字时,我可以看到与名字相同的数据。
我正在尝试建立一对多的关系。
我有 2 个数据模型:
import Foundation
import CoreData
@objc(Items)
class Items: NSManagedObject
@NSManaged var count: NSNumber
@NSManaged var name: String
@NSManaged var cost: NSSet
import Foundation
import CoreData
@objc(Costs)
class Costs: NSManagedObject
@NSManaged var costsDate: NSDate
@NSManaged var costsName: String
@NSManaged var costsValue: NSNumber
@NSManaged var account: Items
这是addAccount
(第一个 VC 的名称)的保存操作:
@IBAction func saveButtonPressed(sender: UIBarButtonItem)
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Items", inManagedObjectContext: managedObjectContext!)
let account = Items(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
account.name = cellOneNameTextField.text
if cellTwoCountTextField.text.isEmpty
else
account.count = (cellTwoCountTextField.text).toInt()!
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Items")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
self.navigationController?.popViewControllerAnimated(true)
这是addCost
的保存动作:
@IBAction func saveButtonTapped(sender: UIBarButtonItem)
// CoreData Access
let appDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var managedObjectContext = appDelegate.managedObjectContext
let entityDescription = NSEntityDescription.entityForName("Costs", inManagedObjectContext: managedObjectContext!)
let cost = Costs(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext!)
cost.costsName = cellThreeNoteTextField.text
cost.costsValue = (cellOnePriceTextField.text).toInt()!
cost.costsDate = datePicker.date
// Saving data
appDelegate.saveContext()
var request = NSFetchRequest(entityName: "Costs")
var error:NSError? = nil
var results:NSArray = managedObjectContext!.executeFetchRequest(request, error: &error)!
for res in results
println(res)
delegate?.refreshTable()
self.navigationController?.popViewControllerAnimated(true)
【问题讨论】:
【参考方案1】:我不知道你是否在某个地方这样做,但你的Items
应该使用来自Items
的cost
变量将Count
对象附加到自身。类似的东西:
let account = Items(...)
let cost = Cost(...)
account.cost.addObject(cost)//and changing your var cost:NSSet into var cost:NSMutableSet
//then save Items
(addObject没试过,原理你懂的)
【讨论】:
以上是关于一对多关系CoreData Swift的主要内容,如果未能解决你的问题,请参考以下文章
Swift 2.0 一对多的关系——仍然是 NSOrderedSet?
Swift 2.1 Core Data - 保存具有一对多关系的数据,但如果已经存在则不要添加异构数据
Swift、CoreData 和多对多关系:如何访问子项的顺序?