可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
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) */
回答2:
As of Xcode 7 and Swift 2.0 (see release note #17583057), you are able to just add the following definitions to the generated extension file:
extension PersonModel {
// This is what got generated by core data
@NSManaged var name: String?
@NSManaged var hairColor: NSNumber?
@NSManaged var parents: NSSet?
// This is what I manually added
@NSManaged func addParentsObject(value:ParentModel)
@NSManaged func removeParentsObject(value:ParentModel)
@NSManaged func addParents(value:Set<ParentModel>)
@NSManaged func removeParents(value:Set<ParentModel>)
}
This works because
The NSManaged attribute can be used with methods as well as
properties, for access to Core Data’s automatically generated
Key-Value-Coding-compliant to-many accessors.
Adding this definition will allow you to add items to your collections. Not sure why these aren't just generated automatically...
回答3:
Core Data in Objective C automatically creates setter methods (1):
By default, Core Data dynamically creates efficient public and primitive get and set accessor methods for modeled properties (attributes and relationships) of managed object classes. This includes the key-value coding mutable proxy methods such as addObject: and removes:, as detailed in the documentation for mutableSetValueForKey:—managed objects are effectively mutable proxies for all their to-many relationships.
As things currently stand with Swift in Xcode6-Beta2, you'd have to implement those accessors yourself. For example if you have an unordered to-many relationship, from Way
to Node
, you'd implement addNodesObject
like this:
class Way : NSManagedObject {
@NSManaged var nodes : NSSet
func addNodesObject(value: Node) {
self.mutableSetValueForKey("nodes").addObject(value)
}
}
Key here is that you'd have to use mutableSetValueForKey
/ mutableOrderedSetValueForKey
/ mutableArrayValueForKey
. On these sets / arrays, you can call addObject and they'll be stored on the next flush.
回答4:
Expanding on the solution above one to many relationships are NSMutableSet so this allows you to directly add or remove the Person NSManagedObject to the Roles in this case a Person has one Role and Roles have many Person(s)
I have tested this solution under Xcode Beta-3 and this works!
This code takes out the Department to simplify showing the one to one and one to many code required to access Roles from a Person and Persons from a Role.
import CoreData
@objc(Person) class Person: NSManagedObject {
@NSManaged var name: String
//One to One relationship in your Model
@NSManaged var roles: Roles
}
@objc(Roles) class Roles: NSManagedObject {
@NSManaged var role: String
//One to Many relationship in your Model
@NSManaged var persons: NSMutableSet
}
extension Roles {
func addPersonsObject(value: Person) {
self.persons.addObject(value)
}
func removePersonsObject(value: Person) {
self.persons.removeObject(value)
}
func addPersons(values: [Person]) {
self.persons.addObjectsFromArray(values)
}
func removePersons(values: [Person]) {
for person in values as [Person] {
self.removePersonsObject(person)
}
}
}
回答5:
You can just use a typed Set
instead which is far easier. Following the example provided by @Nycen and @lehn0058 in the previous answer, you can just write:
extension PersonModel {
@NSManaged var parents: Set<ParentModel>?
}
And then use the insert
and remove
methods of the Set
.
回答6:
As of Xcode 8 and Swift 3.0, Xcode now generates accessors for relationships. For example, I have an NSManagedObject class Store, that has a one to many relationship with Items; I've called that relationship SellsItems. The generated class for Store now has the following extension to add and remove from SellsItems. Adding or removing items to the relationship is as simple as calling these functions.
// MARK: Generated accessors for sellsItems
extension Store {
@objc(addSellsItemsObject:)
@NSManaged public func addToSellsItems(_ value: Item)
@objc(removeSellsItemsObject:)
@NSManaged public func removeFromSellsItems(_ value: Item)
@objc(addSellsItems:)
@NSManaged public func addToSellsItems(_ values: NSSet)
@objc(removeSellsItems:)
@NSManaged public func removeFromSellsItems(_ values: NSSet)
}
回答7:
As you only need to set one side of a relationship for both to be set nowadays, it's particularly simple if you have a 1<->many relationship, e.g. a Department object has multiple Person objects, then you can just use:
aPerson.department = aDepartment
If you check you'll find that aDepartment.people (assuming that is the reciprocal relationship you've set up) will now contain the 'aPerson' Person object.
If the relationship is many<->many then one of the more complex solutions above appears necessary.
回答8:
Let's say you have the following entities:
In your Person
entity, they have a to-many relationship with Role
and to-one with Department
. Your managed object might look something like this:
class Person : NSManagedObject
{
@NSManaged var roles : Array<Role>
@NSManaged var department : Department
}
Relationships with inverses (all should have them) only require one side to be set for the link to be established.
For example, if you set a Person
's department
property to a Department
object, the inverse Department.people
property would now also have this Person
object contained inside.