Swift 一对多关系

Swift One to many relationship

我有两个实体,用户和任务。它们是一对多关系的链接器,这就是它们的样子

import Foundation
import CoreData
@objc(User)
class User: NSManagedObject {
    @NSManaged var id: String
    @NSManaged var name: String
    @NSManaged var task: NSSet
}

import Foundation
import CoreData

@objc(Task)
class Task: NSManagedObject {

    @NSManaged var context: String
    @NSManaged var date: String
    @NSManaged var detail: String
    @NSManaged var folder: String
    @NSManaged var id: String
    @NSManaged var responsable: String
    @NSManaged var status: String
    @NSManaged var summary: String
    @NSManaged var user: User

}

xcdatamodel 上的关系是:

relationship: user, destination: User, Inverse: task  for Task
relationship: task, destination: Task, Inverse: user  for User

我有我的 fetchedResultController 让我在任务上执行我的请求 table:

func getFetchedResultsController(String) -> NSFetchedResultsController{
    frc = NSFetchedResultsController(fetchRequest: taskFetchRequest(folder), managedObjectContext: context!, sectionNameKeyPath: nil, cacheName: nil)
    return frc
}

func taskFetchRequest(String) -> NSFetchRequest {
    //on choisit sur quel Entity on travaille
    let fetchRequest = NSFetchRequest(entityName: "Task")
    //on Choisit sur quel attribut on place l'Order By. Ici sur Summary en Ascendant
    let predicate = NSPredicate(format: "folder = %@", folder)
    let sortDescriptor = NSSortDescriptor(key: "summary", ascending: true)
    fetchRequest.predicate = predicate
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

在两个实体上,我有一个共同的属性,UseridTaskresponsable 是相同的东西,我需要做的是,对于 135482dfsq4g1 负责的任务,打印用户实体的相应名称(因此 ID 135482dfsq4g1

我已经做了一些测试,但没有效果,像这样:

var task : Task?
var user : User?
if(task?.responsable == user?.id){
        OwnerTextField.text = user?.name
    }else{
        println(task?.responsable)
        println(user?.id)
        OwnerTextField.text = ""
    }

找到了 task?.responsable 但找不到 user?.id,所以我无法比较:

Optional("76bbfe695318d471a541bc3333e58eea28acae54")
nil

如有任何帮助,我们将不胜感激。

此致。

只需删除 responsible 属性 并将关系 user 重命名为 responsible.你将获得

NSManaged var responsable: User

并获得 responsible?.name(和 responsible?.id,如果你真的需要的话)会很简单。