swiftcore-datansuuid

storing NSUUID in Core Data causing error


i'm currently trying to save bluetooth device's NSUUID into core data with my code as follow:

let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context = appDel.managedObjectContext
let newDevice = NSEntityDescription.insertNewObjectForEntityForName("Devices", inManagedObjectContext: context)
newDevice.setValue(connectingPeripheral.identifier, forKey: "identifier")
newDevice.setValue(TextField.text, forKey: "name")
do{
try context.save()
} catch _ as NSError{

}

error happens at

newDevice.setValue(connectingPeripheral.identifier, forKey: "identifier")

due to i can't store NSUUID into SQLite database. The only way i can think of is to convert the NSUUID into String and store into SQLite. But it is not so appropriate. Can anyone suggest me how to store NSUUID into SQLite? Thank you


Solution

  • If I wanted to save an NSUUID and later get back an instance of the same object, I'd declare the property to use the Core Data "transformable" type. For any class that conforms to the NSCoding protocol (which NSUUID does), Core Data will automatically invoke NSCoding methods to save/load an instance of the original class. Then I could just assign an NSUUID as the attribute value, and later read back an NSUUID, and Core Data would handle converting it to/from a form that it knows how to handle.