Last active
October 9, 2015 16:22
-
-
Save perlmunger/32d8ba0b277ce9bb1618 to your computer and use it in GitHub Desktop.
Safely Set Values For Key On Managed Objects In Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSManagedObject { | |
func safeSetValuesForKeys(dictionary:[NSObject:AnyObject]) { | |
let attributes: [NSObject:AnyObject] = self.entity.attributesByName | |
var finalValue : AnyObject? = nil | |
for (attribute, value) in attributes { | |
if let val : NSNull = value as? NSNull { | |
continue; | |
} | |
finalValue = dictionary[attribute] | |
print(finalValue) | |
let attributeType : NSAttributeType = value.attributeType | |
if attributeType == .StringAttributeType { | |
if let val : NSNumber = finalValue as? NSNumber { | |
finalValue = val.stringValue; | |
} | |
} else if (attributeType == .Integer16AttributeType || | |
attributeType == .Integer32AttributeType || | |
attributeType == .Integer64AttributeType || | |
attributeType == .BooleanAttributeType) { | |
if let val : NSString = finalValue as? NSString { | |
finalValue = NSNumber(int: val.intValue) | |
} | |
} else if (attributeType == .FloatAttributeType) { | |
if let val : NSString = finalValue as? NSString { | |
finalValue = NSNumber(double: val.doubleValue) | |
} | |
} else if (attributeType == .DateAttributeType) { | |
if let val : NSString = finalValue as? NSString { | |
// You need to get a date formatter in here to handle dates | |
finalValue = NSManagedObject.dateFormatter.dateFromString(val) | |
} | |
} | |
if let stringAttrib = attribute as? NSString { | |
self.setValue(finalValue, forKey: stringAttrib as String) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment