-1

I'm trying to use Core Data and make use of computed properties. Let's assume I have three attributes managed by Core Data, firstname, lastname and company, all Strings. Now I want to create a computed property looking like "firstname lastname - company" to e.g. show in a NSPopUpButton. Since I can't use custom getters for NSManaged properties I was trying to just create a normal computed variable which works, but if I change any of the Core Data attributes it doesn't get recomputed. Am I trying something which could be done much easier?

Daniel
  • 436
  • 3
  • 14
  • Looks like you are looking for a transient property: http://davemeehan.com/technology/objective-c/core-data-transient-properties-on-nsmanagedobject – Mike D Feb 23 '15 at 18:23
  • See this answer for swift transient properties: http://stackoverflow.com/a/26614161/3810673 – Ian Feb 23 '15 at 20:15
  • @MikeD: Your link refers to Objective-C. Doesn't work that way in Swift unfortunately. – Daniel Feb 24 '15 at 09:06
  • @Bluehound: In my understanding transient properties and computed properties are quite different things. One is talking about the storage (transient) where it is exclusively kept in memory and not written to disk whereas computed talks about, well, computed values. – Daniel Feb 24 '15 at 09:07
  • Maybe you want to use a NSFetchedResultsController, then set the delegate to your class, and when the results change, your class will be notified and you can update your "firstname lastname - company" value – lzl Feb 25 '15 at 18:02

2 Answers2

0

Using Swift you can calculate the values when you fetch the values from Core Data by overriding the awakeFromFetch() function. This function will execute whenever you retrieve a managed object from the persistent store.

You need to override this function in your managed object:

override public func awakeFromFetch() {
    let newValue = value1 + value2

In the above example your "newValue" will be calculated using the existing value1 and value2 parameters of your managed object

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
bluaura
  • 21
  • 7
-2

I got an answer on the Apple Dev Forums.

Just implemented:

class func keyPathsForValuesAffectingComputed() -> Set<String> {
    return ["firstname", "lastname", "company"]
}
Daniel
  • 436
  • 3
  • 14