Setting an NSManagedObject relationship in Swift

情到浓时终转凉″ 提交于 2019-11-28 04:21:31
iluvcapra

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) */
lehn0058

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...

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.

BadDogApps

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)
        }
    }

}

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.

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)
}

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.

Let's say you have the following entities:

  • Person
  • Role
  • Department

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!