如何使用一对多的 NSManagedObject class 生成的访问器?

How to use generated accessors one-to-many of NSManagedObject class?

我有一个核心数据库,其中包含 Post 和客户端实体。 Post 具有一对多关系。

我对 self.addToClients(newClient) 行有错误:

ERROR Cannot invoke 'addToClients' with an argument list of type '(NSManagedObject)'

我的两个实体的定义:

public class Post: NSManagedObject {    

   @nonobjc public class func postFetchRequest() -> NSFetchRequest<Post> {
        return NSFetchRequest<Post>(entityName: "Post")
    }

    @NSManaged public var id: NSNumber
    @NSManaged public var content: String
    @NSManaged public var clients: NSSet?


     func insertClientFor(url:String, completion: @escaping(Bool) -> ()) {

        let managedContext = CoreDataManager.sharedManager.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Client",in: managedContext)!
        let newClient = NSManagedObject(entity: entity, insertInto: managedContext)

        newClient.setValue(url, forKey: "url")

        self.addToClients(newClient) //ERROR Cannot invoke 'addToClients' with an argument list of type '(NSManagedObject)'

        do {
            try managedContext.save()
            completion(true)
        } catch let error as NSError {
            print("Could not save. \(error), \(error.userInfo)")
            completion(false)

        }
    }
}


// MARK: Generated accessors for clients
extension Post {

    @objc(addClientsObject:)
    @NSManaged public func addToClients(_ value: Client)

    @objc(removeImagesStripObject:)
    @NSManaged public func removeFromClients(_ value: Client)

    @objc(addImagesStrip:)
    @NSManaged public func addToClients(_ values: NSSet)

    @objc(removeImagesStrip:)
    @NSManaged public func removeFromClients(_ values: NSSet)

}

@objc(Client)
public class Client: NSManagedObject {

    @NSManaged public var url: String
    @NSManaged public var post: Post

    @nonobjc public class func fetchRequest() -> NSFetchRequest<ImageStrip> {
         return NSFetchRequest<ImageStrip>(entityName: "ImageStrip")
     }  
}

我不明白哪里出了问题。

您是否尝试过将 newClient 转换为 Client

let newClient = NSManagedObject(entity: entity, insertInto: managedContext) as? Client

let newClient = NSEntityDescription.insertNewObject(forEntityName: String(describing: Client.self), into: managedContext) as? Client