Swift and CoreData, problems with relationship (NSSet) - [NSSet intersectsSet:]: set argument is not an NSSet

前端 未结 2 1904
天涯浪人
天涯浪人 2021-02-19 19:16

I\'ve been trying to get my head around adding objects in relationships using CoreData and Swift. I am at a loss, I do not understand why my code does not work. I am trying to a

相关标签:
2条回答
  • 2021-02-19 20:13

    If you use the objective C generated NSManagedObject subclasses, they include custom methods for adding a single object - I think these are tried and tested and seem better than what is currently there for swift.

    Theoretically you would just need to just set the new set with whatever new set you created. One option would be:

        var matchobjs = matches.allObjects as [Event]
        matchobjs.append(event)
        matches = NSSet(array: matchobjs)
    

    However the error looks very similar to this post:

    Which to me looks like theres something fishy going on again with many-to-many relationships...

    0 讨论(0)
  • 2021-02-19 20:19

    Yesss!! I found the answer!

    I had created a new function in the class Events.swift (the other side of the relationship).

    I had written the following code:

    import Foundation
    import CoreData
    
    class Event: NSManagedObject {
    
        @NSManaged var timeStamp: NSDate
        @NSManaged var teams: NSSet
    
    }
    
    extension Event {
    
        func addTeamToEvent(team:Teams) {
            var teamz = self.mutableSetValueForKey("teams")
            teamz.addObject(team)
        }
    
        func getNumberOfTeams() -> Int {
            return self.teams.count;
        }
    
        func getTeams() -> [Teams] {
            var tmpsak: [Teams]
            tmpsak = self.teams.allObjects as [Teams]
            tmpsak = self.teams.allObjects as [Teams]
    
            return tmpsak
        }
    
    }
    

    which I thought was unrelated. However, renaming getTeams to getTeamsAsArray removed the problem. I am guessing that CoreData, when filling in the other end of the relationship, uses a built-in function called getTeams() (since the other class was called Teams). I accidentally overrode(?) it, causing it to fail.

    Thank you for your suggestions, and I hope this can be helpful to someone else!

    On a somewhat related note, a bug with similar symptoms was identified a few years ago (and appears to still be present), that shows itself in auto-generated code when using ordered many-to-many relationships.

    0 讨论(0)
提交回复
热议问题