简体   繁体   中英

iOS Core Data transformable

I am relatively new to iOS CoreData implementation. Here is my problem:

I have an entity which has an 'assets' field that may contain one or many different types of objects. It is in a sub-object of another. What is the best way to store this and how do I retrieve it.

My pseudo code example:

extension Group (
    @NSManaged public var created: NSDate?
    @NSManaged public var type: String?
    @NSManaged public var people: NSSet?
}

extension Person {
    @NSManaged public var created: NSDate?
    @NSManaged public var type: String?
    @NSManaged public var asset: NSObject?  //marked as transformable in data model
}

In the Person.asset it can be one or a combination of several different class of objects:

extension Car {..}
extension House { ...} 
etc. 

My current method of saving is creating the individual type of asset and add to the person;

let myGroup = Group(...)
let person1 = Person(...)
let hisCar = Car(..) 
person1.asset = hisCar
myGroup.addPersonObject(person: person1)

let person2 = Person(...)
let hisHouse = House(...) 
person2.asset = hisHouse
myGroup.addPersonObject(person: person2)

BEFORE I save context the following seems to work and I can access the Person objects by:

let peopleInGroup = Group.people!
for case let person as Person in peopleInGroup {
    if person.type != "" {
        print (person.type as! String)
    }
}

Until I save the context and Reload the application. On load of the application I fetch Group object and then try to execute the same code above. It appears to be pointing at the right person object, but fails on the person.type line and I end up wit an error: [error] error: exception handling request: , -[Asset initWithCoder:]: unrecognized selector sent to instance 0x60c00027e040 with userInfo of (null)

I believe I might need to do some sort of encoding on the asset field when I am saving and fetching? The error is referencing the asset even though I am trying to access the type property on the person. Thanks in advance for any help.

Transformable attributes work by using NSCoding on the attribute value. It doesn't really matter if asset has multiple types as long as all of them conform to NSCoding . If adding that to your various types is a problem, you'll have to find some other way to save the asset info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM