I have a core data entity which has an attribute that can represent different types of values (int, double, date, string).
Would it lead to problems (e.g. loss of precision) somewhere down to line if I convert all these values to a String and then back?
@nsmanaged var storedType : Int
@nsmanaged var storedValue : String
var value: Any? {
{
set {
switch newValue
{
case is Int:
self.storedValue = String(newValue)
self.storedType = 0
...
case is string
self.storedValue = newValue
self.storedType = 5
}
}
get {
switch newValue
{
case is 0:
return Int(self.storedValue)
...
case is 5:
return self.storedValue
}
}
}
}
While I would think long and hard about the architecture first I agree there may be a case for this functionality and where else than SO should this question be asked*.
One option is to use the transformable property type. This type allows coreData to store any object that is NSCoding compliant (NSArray, NSDictionary etc.) and also NSString and NSNumber I believe.
Thus you can retrieve that object as the generic type (id in Objective-C, don't know the equivalent in swift) and then query it for type and cast it to whatever you need.
The downside of this approach is of course that you loose a lot of the coreData power in querying the store as the values you store as transformable attributes become more or less opaque to predicates and such. However it works fine for walking the core data structure with key paths.
*) I believe I read that the equivalent variant data type in VB is one of Joel Spolsky's contributions to that language...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With