Swift和CoreData,关系问题(NSSet) - [NSSet intersectsSet:]:set参数不是NSSet

时间:2014-08-13 16:45:23

标签: ios core-data swift nsset

我一直在尝试使用CoreData和Swift在关系中添加对象。我很茫然,我不明白为什么我的代码不起作用。我正在尝试添加一个"事件"到了#34;团队"。我找不到接受的答案(应该有效)和我的代码(没有)之间的区别。

Teams.swift:

import Foundation
import CoreData

class Teams: NSManagedObject {

    @NSManaged var teamName: String
    @NSManaged var matches: NSSet

}

extension Teams {

    func addEventToTeam(event:Event) {
        //self.mutableSetValueForKeyPath("matches").addObject(event)

        var matchez: NSMutableSet

        matchez = self.mutableSetValueForKey("matches")
        matchez.addObject(event)


        //var manyRelation = self.valueForKeyPath("matches") as NSMutableSet
        //manyRelation.addObject(event)
    }

    func getTeamName() -> String {
        return teamName
    }


}

调用代码(从配置视图):

import UIKit
import CoreData

class DetailViewController: UIViewController, NSFetchedResultsControllerDelegate {

    var managedObjectContext: NSManagedObjectContext? = nil

    @IBOutlet weak var detailDescriptionLabel: UILabel!


    var detailItem: AnyObject? {
        didSet {
            // Update the view.
            self.configureView()
        }
    }

    func configureView() {
        // Update the user interface for the detail item.
        if let detail: Event = (self.detailItem as? Event) {
        //if let detail: AnyObject = self.detailItem {

            if let label = self.detailDescriptionLabel {
                label.text = detail.valueForKey("timeStamp").description

                self.insertNewObject(self);
                label.text = String(detail.getNumberOfTeams())

                //detail.getTeams().
                var hej: Array<Teams>
                hej = detail.getTeams()

                label.text = "tjosan"

                for tmpTeam : Teams in hej {
                    label.text = label.text + ", " + tmpTeam.getTeamName()
                }


            }
        }

        if true {


        }


    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.configureView()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    var fetchedResultsController: NSFetchedResultsController {
        if _fetchedResultsController != nil {
            return _fetchedResultsController!
            }

            let fetchRequest = NSFetchRequest()
            // Edit the entity name as appropriate.
            let team = NSEntityDescription.entityForName("Teams", inManagedObjectContext: self.managedObjectContext)
            fetchRequest.entity = team

            // Set the batch size to a suitable number.
            fetchRequest.fetchBatchSize = 20

            // Edit the sort key as appropriate.
            let sortDescriptor = NSSortDescriptor(key: "teamName", ascending: false)
            let sortDescriptors = [sortDescriptor]

            fetchRequest.sortDescriptors = [sortDescriptor]

            // Edit the section name key path and cache name if appropriate.
            // nil for section name key path means "no sections".
            let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master")
            aFetchedResultsController.delegate = self
            _fetchedResultsController = aFetchedResultsController

            var error: NSError? = nil
            if !_fetchedResultsController!.performFetch(&error) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                //println("Unresolved error \(error), \(error.userInfo)")
                abort()
            }

            return _fetchedResultsController!
    }    
    var _fetchedResultsController: NSFetchedResultsController? = nil



    func insertNewObject(sender: AnyObject) {
        let context = self.fetchedResultsController.managedObjectContext
        let team = self.fetchedResultsController.fetchRequest.entity
        let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(team.name, inManagedObjectContext: context) as Teams

        // If appropriate, configure the new managed object.
        // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
        newManagedObject.setValue("Lagur Namnurk", forKey: "teamName")

        newManagedObject.addEventToTeam(self.detailItem as Event)


        // Save the context.
        var error: NSError? = nil
        if !context.save(&error) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            //println("Unresolved error \(error), \(error.userInfo)")
            abort()
        }
    }



}

错误讯息:

2014-08-13 18:38:46.651 Score Calculator 2[10538:829319] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSSet intersectsSet:]: set argument is not an NSSet'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001028a53e5 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x00000001043b8967 objc_exception_throw + 45
    2   CoreFoundation                      0x000000010280fc6c -[NSSet intersectsSet:] + 940
    3   Foundation                          0x0000000102d0c4a6 NSKeyValueWillChangeBySetMutation + 156
    4   Foundation                          0x0000000102c804fa NSKeyValueWillChange + 386
    5   Foundation                          0x0000000102d0c3fb -[NSObject(NSKeyValueObserverNotification) willChangeValueForKey:withSetMutation:usingObjects:] + 310
    6   CoreData                            0x00000001024178d7 -[NSManagedObject(_NSInternalMethods) _includeObject:intoPropertyWithKey:andIndex:] + 551
    7   CoreData                            0x0000000102418294 -[NSManagedObject(_NSInternalMethods) _maintainInverseRelationship:forProperty:forChange:onSet:] + 276
    8   CoreData                            0x0000000102416ef2 -[NSManagedObject(_NSInternalMethods) _didChangeValue:forRelationship:named:withInverse:] + 562
    9   Foundation                          0x0000000102c835d6 NSKeyValueNotifyObserver + 356
    10  Foundation                          0x0000000102c827fd NSKeyValueDidChange + 466
    11  Foundation                          0x0000000102d0c7ee -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:withSetMutation:usingObjects:] + 118
    12  CoreData                            0x00000001024180b0 -[NSManagedObject didChangeValueForKey:withSetMutation:usingObjects:] + 80
    13  CoreData                            0x000000010242fa11 -[_NSNotifyingWrapperMutableSet addObject:] + 161

编辑:一些澄清。团队和活动有着多对多,无序的关系。

2 个答案:

答案 0 :(得分:11)

YESSS !!我找到了答案!

我在Events.swift类中创建了一个新函数(关系的另一面)。

我写了以下代码:

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
    }

}
我认为这是无关的。但是,将getTeams重命名为getTeamsAsArray可以解决问题。我猜测CoreData在填充关系的另一端时,使用了一个名为getTeams()的内置函数(因为另一个类叫做Teams)。我不小心覆盖了(?)它,导致它失败。

感谢您的建议,我希望这对其他人有所帮助!

在一个有点相关的说明中,几年前发现了一个类似症状的错误(并且似乎仍然存在),当使用有序 many-to时,它会在自动生成的代码中显示出来 - 很多关系。

答案 1 :(得分:1)

如果您使用目标C生成的NSManagedObject子类,它们包含用于添加单个对象的自定义方法 - 我认为这些是经过试验和测试的,并且看起来比目前swift的更好。

理论上,您只需要使用您创建的任何新集来设置新集。一种选择是:

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

然而,该错误与this post:

非常相似

对我来说,看起来像是多情多彩的关系再次发生了什么......