Rob
Rob

Reputation: 777

Core data transient values with Swift

Does anyone know, or have an example of, how to handle core data transient values with Swift? I know to use @NSManaged before the properties, but can't figure out how to code the logic to build the transient values using Swift.

Upvotes: 15

Views: 4663

Answers (2)

D4ttatraya
D4ttatraya

Reputation: 3404

Check mark the transient field in your data model for particular attribute(e.g. sectionTitle).
Create class for that entity, it will look something like

 class Message: NSManagedObject {

    @NSManaged var body: String?
    @NSManaged var time: NSDate?
    @NSManaged var sectionTitle: String?
}

Edit it and make it like this:

class Message: NSManagedObject {

    @NSManaged var body: String?
    @NSManaged var time: NSDate?

    var sectionTitle: String? {
        return time!.getTimeStrWithDayPrecision()
        //'getTimeStrWithDayPrecision' will convert timestamp to day
        //just for e.g.
        //you can do anything here as computational properties
    }
}

Update- Swift4
Use @objc tag for Swift 4 as:

@objc var sectionTitle: String? {
   return time!.getTimeStrWithDayPrecision()
}

Upvotes: 16

Hadhi
Hadhi

Reputation: 76

We should use willAccessValueForKey and didAccessValueForKey to support KVO

Upvotes: 1

Related Questions