Setting an NSManagedObject relationship in Swift
core-data, ios, macos, nsmanagedobject, swift
Solution
Yeah that's not going to work anymore, Swift cannot generate accessors at runtime in this way, it would break the type system.
What you have to do is use the key paths:
var manyRelation = myObject.valueForKeyPath("subObjects") as NSMutableSet
manyRelation.addObject(subObject)
/* (Not tested) */
Problem
How does one add an object to a relationship property in an `NSManagedObject` subclass in Swift? In Objective-C, when you generate an `NSManagedObject` subclass in Xcode from the data model, there's an automatically generated class extension which contains declarations like: ``` @interface MyManagedObject (CoreDataGeneratedAccessors) - (void)addMySubObject: (MyRelationshipObject *)value; - (void)addMySubObjects: (NSSet *)values; @end ``` However Xcode currently lacks this class generation capability for Swift classes. If I try and call equivalent methods directly on the Swift object: ``` myObject.addSubObject(subObject) ``` ...I get a compiler error on the method call, because these generated accessors are not visible. I've declared the relationship property as `@NSManaged`, as described in the documentation. Or do I have to revert to Objective-C objects for data models with relationships?