【发布时间】:2016-06-01 10:48:26
【问题描述】:
我正在尝试将多个核心数据关系添加到一个对象。这是我的 CoreData 表:
我正在使用此代码向数据库添加对象:
for data in rawData{
if let itemID = Int(data.1.array![0].string!){
if let seriesID = Int(data.1.array![1].string!){
if let frontPictureId = Int(data.1.array![3].string!){
if let backPictureId = Int(data.1.array![4].string!){
if let itemDescription = data.1.array![5].string{
if let catatalogCodes = data.1.array![6].string{
if let itemName = data.1.array![7].string{
//Retrieve Serie for current stamp
var currentSerie: Serie!
privateMOC.performBlockAndWait{
let serieFetch = NSFetchRequest(entityName: "Serie")
serieFetch.predicate = NSPredicate(format: "seriesID == %d", seriesID)
do {
let results = try privateMOC.executeFetchRequest(serieFetch) as! [Serie]
if results.count > 0 {
currentSerie = results.first
}
} catch let error as NSError {
print("Error: \(error) " +
"description \(error.description)")
}
}
let stamp = NSEntityDescription.insertNewObjectForEntityForName("Stamp", inManagedObjectContext: privateMOC) as! Stamp
stamp.itemID = itemID
stamp.frontPictureID = frontPictureId
stamp.backPictureID = backPictureId
stamp.itemDescription = itemDescription
stamp.catalogCodes = catatalogCodes
stamp.itemName = itemName
//Make the series Relationship
//TODO: - Add RelationShip
arrayOfStamps.append(stamp)
}
}
}
}
}
}
}
}
currentCountry.mutableOrderedSetValueForKey("serie").addObjectsFromArray(arrayOfStamps)//Add Stamp to the database
privateMOC.performBlockAndWait(){
do {
try privateMOC.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}
但是,在 TODO-:添加关系的那一行需要添加什么内容?当我尝试使用这个时:currentSerie.mutableOrderedSetValueForKey("stamps").addObject(stamp)//Add Stamp to serie Ik 得到一个错误,即类型系列,不包含 mutableOrderdSetValueForKey。
邮票对象需要同时与国家和意甲有关系。我使用以下代码创建与国家对象的关系:currentCountry.mutableOrderedSetValueForKey("serie").addObjectsFromArray(arrayOfStamps)//Add Stamp to the database
所以我需要在新添加的图章中添加两个关系。如何正确有效地做到这一点?
【问题讨论】:
-
不,因为在这里我想向一个对象添加 multiple 关系,这并不像我期望的那样工作。这就是我问这个问题的原因。我希望澄清有所帮助。
标签: ios swift core-data relationship