核心数据添加关系值

时间:2016-03-31 21:02:18

标签: core-data mutable nsset

我有两个实体:

extension Meet {

    @NSManaged var meetAllAroundScore: NSNumber?
    @NSManaged var meetBarPlace: String?
    @NSManaged var meetBarScore: NSNumber?
    @NSManaged var meetBeamPlace: String?
    @NSManaged var meetBeamScore: NSNumber?
    @NSManaged var meetDate: String?
    @NSManaged var meetDateSort: String?
    @NSManaged var meetFloorPlace: String?
    @NSManaged var meetFloorScore: NSNumber?
    @NSManaged var meetLocation: String?
    @NSManaged var meetName: String?
    @NSManaged var meetStatus: String?
    @NSManaged var meetTime: String?
    @NSManaged var meetTimeSort: String?
    @NSManaged var teamPlace: String?
    @NSManaged var gymnasts: NSSet?

}

extension Gymnast {

    @NSManaged var age: NSNumber?
    @NSManaged var email: String?
    @NSManaged var firstName: String?
    @NSManaged var gender: String?
    @NSManaged var isActive: String?
    @NSManaged var lastName: String?
    @NSManaged var level: NSNumber?
    @NSManaged var picture: NSData?
    @NSManaged var telephone: String?
    @NSManaged var usag: String?
    @NSManaged var meets: NSSet?

}

之前我就如何为所有体操运动员举行新的比赛提出了这个问题,并被告知我需要在将关系改变为多对多之后添加这些扩展。

extension NSManagedObject {
    func addObject(value: NSManagedObject, forKey key: String) {
        let items = self.mutableSetValueForKey(key)
        items.addObject(value)
    }

    func removeObject(value: NSManagedObject, forKey key: String) {
        let items = self.mutableSetValueForKey(key)
        items.removeObject(value)
    }
}

有人能指出我出错的地方吗?

if let meetname = meetNameText.text {

                item.meetName = meetname

                //let newMeet = meetNameText.text
                let newMeet = item.gymnasts!.mutableCopy() as! NSMutableSet
                let items = self.mutableSetValueForKey("gymnasts")
                items.addObject(newMeet)

1 个答案:

答案 0 :(得分:0)

首先,你必须让所有体操运动员都进入一场并创造一个新的见面。要将新会面的体操运动员设置为你所做的体操运动员:

newMeet.gymnasts = setOfGymnasts

这取代了所有相关的体操运动员,但新的比赛没有。

在现有的会面中添加一名体操运动员:

let items = meet.mutableSetValueForKey("gymnasts")
items.addObject(gymnast)

在现有的比赛中添加一组体操运动员:

let items = meet.mutableSetValueForKey("gymnasts")
items.unionSet(setOfGymnasts)

您还可以使用NSMutableSet的其他方法,例如removeObjectminusSet