i working the first time with relationships in core data. what i have now:
let appdelegate = NSApplication.shared().delegate as! AppDelegate
let context = appdel
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<Person>(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"