swift 3 - create entry with relationship

前端 未结 1 598
梦毁少年i
梦毁少年i 2021-01-23 18:51

i working the first time with relationships in core data. what i have now:

let appdelegate = NSApplication.shared().delegate as! AppDelegate
let context = appdel         


        
1条回答
  •  别那么骄傲
    2021-01-23 19:09

    You have to perform a fetch to check if the person is available.

    Then assign the person to the book (to-one relationship) for example

    let personName = "John"
    let fetchRequest = NSFetchRequest(entityName: "Person")
    let predicate = NSPredicate(format: "name == %@", personName)
    fetchRequest.fetchLimit = 1
    do {
        let persons = try context.fetch(fetchRequest)
        if let person = persons.first {
            newBook.person = person
        }
    } catch {
       print(error)
    }
    

    The code takes advantage of the Swift 3 generic types.

    Edit:

    The declaration of the NSManagedObject subclasses are wrong.

    According to your model Person must be

    extension Person {
        @NSManaged public var name: String?
        @NSManaged public var books: NSSet
    }
    

    and Books must be

    extension Book {
        @NSManaged public var title: String?
        @NSManaged public var person: Person?
    }
    

    Consider to make at least the name and title attributes non-optional.


    PS: Since you are using NSManagedObject subclasses you can use the property directly with dot notation rather then KVC

    newPerson.name = "Max"
    

    0 讨论(0)
提交回复
热议问题