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.
Asked
Active
Viewed 4,445 times
15
-
2Having @NSManaged does not allow me to create a getter for the transient property in Swift. I would like to know how transient property works in Swift as well. – Sam Aug 29 '14 at 17:05
-
possible duplicate of [CoreData Swift and transient attribute getters](http://stackoverflow.com/questions/25960555/coredata-swift-and-transient-attribute-getters) – Ian Mar 12 '15 at 07:09
-
Did you resolve this issue? Did the given link help? – Orion Mar 22 '16 at 09:07
2 Answers
16
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()
}

D4ttatraya
- 3,344
- 1
- 28
- 50
-
5This works good if "Codegen" in Entity property is set to "manual/none". How to handle it "Codegen" is set to "Category/Extension"? – Satyam Apr 18 '17 at 14:01
-
1With swift 4 I had to use "@objc dynamic var sectionTitle: String? {...}" in a similar case to make it work. – user3687284 Oct 10 '17 at 19:08
-
2The transient property will not work for sort descriptors when used in fetch request. It will give an error as keypath yourTransientVariable not found in entity
with userInfo of (null). you can only filter and sort on non-transient attributes. https://stackoverflow.com/a/17853561/2545465 – Rajan Maheshwari Jun 01 '18 at 19:54