Search code examples
iosswiftcore-datacompiler-errorsxcode6.1

Issue setting up one to many relationship in Swift Core Data


I am in the process of learning Swift and have come across an issue that I can't seem to piece together a solution for.

Currently I have two Entities in my data model: Card and Set

Model Graph

A Set can have many cards, but a Card can only belong to one Set.

My cards relationship is set as To Many:

Model Graph

While my set relationship is set to To One:

Model Graph

For these two Entities, I have the following subclass code:

import Foundation
import CoreData

@objc(Set) class Set: NSManagedObject {

    @NSManaged var code: String
    @NSManaged var name: String
    @NSManaged var cards: NSSet

}

extension Set {
    func addCard(value: Card) {
        self.mutableSetValueForKey("cards").addObject(value)
    }

    func getCards() -> [Card] {
        var cards: [Card]
        cards = self.cards.allObjects as [Card]
        return cards
    }
}

import Foundation
import CoreData

@objc(Card) class Card: NSManagedObject {

    @NSManaged var name: String
    @NSManaged var set: Set

}

I have successfully created and verified a Set with code such as this:

var set = NSEntityDescription.insertNewObjectForEntityForName("Set", inManagedObjectContext: context) as Set
set.name = setName;
set.code = setCode;

context.save(nil)

However, later when I attempt to create Card objects and add them to this set I run into an error. Here is the code I am using for that:

// The json data here is already verified as working fine elsewhere in my code, it just serves as the basis for creating the Card objects
var cards: [AnyObject] = json.valueForKey("cards") as NSArray

for var i = 0; i < cards.count; i++ {
    var cardData = cards[i] as NSDictionary

    var card = NSEntityDescription.insertNewObjectForEntityForName("Card", inManagedObjectContext: context) as Card
    card.name = cardData.valueForKey("name") as String

    set.addCard(card)

    context.save(nil)
}

The error being fired currently reads as follows:

2015-01-19 00:25:42.803 <app name>[4667:113927] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSSet intersectsSet:]: set argument is not an NSSet'

I tried tracking the error as close to the point of failure as possible. It seems to happen in the addCard function in the Set extension. I am guessing I have some very minor error in my code, but since I am pretty new to debugging Swift code I am currently at a loss for where to go next. I actually had the assignment of Cards to a Set working previously, but something I changed must have caused this issue to occur.


Solution

  • You should rename getCards() function in the Set extension, I believe core data use this function name and the issue happened because you override it.