Coredata / SWIFT获得有关系的记录

时间:2016-03-26 10:31:17

标签: swift core-data relationship

核心数据关系仍然存在问题。

示例:

实体用户(idU,NameU =属性) 实体设备(idD,NameD =属性)

core data model 问题:当我创建链接到用户的新设备时,我遇到了Nsset问题。我认为这与许多关系有关

仍未正常工作更新:

代码:

 @IBAction func addDeviceBoutonAction(sender: AnyObject) {

        print("Creation Device debut")
        var nbCharacteres = Int((newDeviceNameTextField.text?.characters.count)!)
        if currentUserName == "" {
           print("Erreur creation device / currentUserName = Vide --> Abort")
          }
          else if nbCharacteres == 0 {
            print("Erreur creation device / newDeviceNameTextField = Vide --> Abort")
          }
          else
          {
          // init du MOC
          let MOC = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
        // creation de la requete sur l'entité User avec un predicat : on recupere que les infos du user selectionné dans le pickerViewUser (on 
        // travaille avec la variable globale currentUserName qui a été initialisée lors du  didSelectRow du pickerViewUser)
        let fetchRequestUser = NSFetchRequest(entityName: "User")
        print("Creation device / trace currentUserName = \(currentUserName)")
        let userPredicate = NSPredicate(format: "userName == %@", currentUserName)
        // On colle le predicat dans la requete
        fetchRequestUser.predicate = userPredicate

        var requestError: NSError?
        let existingUser = (try! MOC.executeFetchRequest(fetchRequestUser)) as! [User]
         print("Creation device / trace existingUser[0].userName = \(existingUser[0].userName)")
        // il faut passer par l'ID plutot que le nom
        // firstUserFound de type User
         let firstUserFound = existingUser[0]
                print("Creation device firstUserFound = \(firstUserFound)")    

        // Insertion d'un nouveau Device dans la base  (relationship n to n entre Device et User)
       let existingDevicesForThisUser = firstUserFound.mutableSetValueForKey("device")

       // Create Item Record
       let newDevice = NSEntityDescription.insertNewObjectForEntityForName("Device",inManagedObjectContext: MOC) as! Device
       //if let newDevice = createRecordForEntity("Device", inManagedObjectContext: MOC) {
        // Set Attributes and values
        newDevice.setValue(NSUUID().UUIDString, forKey: "deviceId")
        newDevice.setValue(newDeviceNameTextField.text, forKey: "deviceName")
        newDeviceNameTextField.text = ""
        self.view.endEditing(true)
        //newDevice.setValue("Device \(newDevice.count + 1)", forKey: "deviceId")
        // Set Relationship
        print("avant relationhips")
        newDevice.setValue(firstUserFound, forKey: "users")

错误: 创作设备首次亮相

创建设备/跟踪currentUserName = toto

创建设备/跟踪existingUser [0] .userName =可选(" toto")

Creation device firstUserFound =(entity:User; id:0xd000000000080000; data:{     devices ="&#34 ;;     userId =" 8A32EAC6-87E2-4CF1-8265-5E7A32ABCEBB&#34 ;;     userName = toto; })

前卫关系

2016-04-02 13:55:13.065 testcoredatarelationships [1568:370426] *由于未捕获的异常终止应用程序' NSInvalidArgumentException',原因:'不可接受的值类型为 - 很多关系:property =" users&#34 ;;期望的类型= NSSet;给定type = testcoredatarelationships.User; value =(entity:User; id:0xd000000000080000; data:{     devices ="&#34 ;;     userId =" 8A32EAC6-87E2-4CF1-8265-5E7A32ABCEBB&#34 ;;     userName = toto; })&#39。 * 首先抛出调用堆栈:

这是错误的: newDevice.setValue(firstUserFound,forKey:" users")

扩展设备{

@NSManaged var deviceId: String?
@NSManaged var deviceName: String?
@NSManaged var cards: NSSet?
**@NSManaged var users: NSSet?**

}

1 个答案:

答案 0 :(得分:1)

您正在使用多对多关系,因此获取插孔设备的最简单方法是获取插孔(带有获取请求),然后向其询问其设备。这导航了这段关系,因此您不需要再次获取。

可以直接获取与具有特定名称的用户有关系的设备,但这样做会更复杂。