viirus viirus - 4 months ago 23
iOS Question

Store NSMeasurement or NSUnit in Core Data

iOS 10 introduces new classes for measurements and units. I would like to either store a NSMeasurement or NSUnit object in my core data database, so that I can store different measurements in my database.

Is there a good way to do this? Since my app would only use a subset of all available units, I could in theory create a string representation of the units and use a switch statement to get the actual unit classes from that when needed. But that feels overly complicated and error prone.

Answer

Both of those classes conform to NSCoding, so you can a store them as "transformable" attributes. As transformables, you read/write object values directly from/to the attribute, and Core Data automatically converts between the object type and NSData as needed. You don't need to do any conversions of your own.