本文介绍了Coredata / SWIFT获取具有关系的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仍然困扰着核心数据关系。



示例:



实体用户(idU,NameU =属性)
实体设备(idD,名称D =属性)




问题:创建与用户链接的新设备时,出现了Nsset问题。我认为这与许多关系有关



仍然无法正常工作UPDATE:



代码:

  @IBAction func addDeviceBoutonAction(sender: AnyObject){

print(创建设备首次亮相)
var nbCharacteres = Int((newDeviceNameTextField.text?.characters.count)!)
如果currentUserName == {
print( Erreur creation device / newDeviceNameTextField)
否则,如果nbCharacteres == 0 {
print( Erreur creation device / newDeviceNameTextField = Vide-> Abort)
}
else
{
// init du MOC
let MOC =(UIApplication.sharedApplication()。delegate as! AppDelegate).managedObjectContext
//创建请求实体用户:在重新选择用户信息后,选择对象ewUser(在
上//遍历变量全局变量currentUserName进行初始化,或者在didSelectRow du pickerViewUser中)
let fetchRequestUser = NSFetchRequest(entityName: User)
print( Creation device / trace currentUserName = \(currentUserName))
让userPredicate = NSPredicate(格式: userName ==%@,currentUserName)
//在上校谓词上,要求
fetchRequestUser。谓词= userPredicate

var requestError:NSError?
让existingUser =(尝试!MOC.executeFetchRequest(fetchRequestUser))为! [用户]
print(创建设备/跟踪现存用户[0] .userName = \(existingUser [0] .userName))
// ilaut passer par l'ID plutot que le nom
// firstUserFound类型的用户
让firstUserFound =现有用户[0]
print(创建设备firstUserFound = \(firstUserFound))

//插入d'un nouveau Device dans la base(与设备和用户之间的关系)
let existingDevicesForThisUser = firstUserFound.mutableSetValueForKey( device)

//创建项目记录
让newDevice = NSEntityDescription.insertNewObjectForEntityForName( Device,inManagedObjectContext:MOC)为!设备
//如果让newDevice = createRecordForEntity( Device,inManagedObjectContext:MOC){
//设置属性和值
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)
//设置关系
print( avant relationshiphips)
newDevice.setValue(firstUserFound, forKey:用户)

错误:
创建设备首次亮相



创建设备/跟踪currentUserName = toto



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



创建设备firstUserFound =(实体:User; id:0xd000000000080000;数据:{
devices =;
userId = 8A32E AC6-87E2-4CF1-8265-5E7A32ABCEBB;
userName = toto;
})



前卫关系



2016-04-02 13:55:13.065 testcoredatarelationships [ 1568:370426] *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'多对多关系的值的不可接受类型:property = users;所需的类型= NSSet;给定类型= testcoredatarelationships.User;值=(实体:用户; ID:0xd000000000080000;数据:{
设备=;
userId = 8A32EAC6-87E2-4CF1-8265-5E7A32ABCEBB;
userName = toto;
})。'
*
第一个调用堆栈:



行有误:
newDevice.setValue(firstUserFound ,forKey:用户)



扩展设备{

  @ NSManaged var deviceId:字符串? 
@NSManaged var deviceName:字符串?
@NSManaged var卡:NSSet?
** @ NSManaged var用户:NSSet吗?**

}

解决方案

您正在使用多对多关系,因此获取千斤顶设备的最简单方法是获取千斤顶(带有获取请求),然后询问它的设备。



可以直接获取与具有特定名称的用户有关系的设备,但操作起来比较复杂。



做到这一点。


Still in trouble with core data relationships.

Example :

Entity User (idU, NameU = attributes)Entity Device (idD, NameD = attributes)

core data modelQuestion : I have a Nsset issue when i create a new device linked to user. i think it is related to the many-many relationships

still not working UPDATE :

code :

 @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")

Error :Creation Device debut

Creation device / trace currentUserName = toto

Creation device / trace existingUser[0].userName = Optional("toto")

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

avant relationhips

2016-04-02 13:55:13.065 testcoredatarelationships[1568:370426] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-many relationship: property = "users"; desired type = NSSet; given type = testcoredatarelationships.User; value = (entity: User; id: 0xd000000000080000 ; data: { devices = ""; userId = "8A32EAC6-87E2-4CF1-8265-5E7A32ABCEBB"; userName = toto;}).'* First throw call stack:

line which is wrong :newDevice.setValue(firstUserFound, forKey: "users")

extension Device {

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

}

解决方案

You're using a many to many relationship so the easiest way to get jacks devices is to get jack (with a fetch request) and then to ask it for its devices. This navigates the relationship so you don't need another fetch.

It's possible to directly fetch devices who have a relationship to a user with a specific name but it's more complicated to do that.

这篇关于Coredata / SWIFT获取具有关系的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 02:42