1

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

wes. i
  • 627
  • 9
  • 26
  • Why is it inappropriate to convert it to a string? NSUUID has a property, UUIDString, for that purpose. – pbasdf Jan 28 '16 at 09:31
  • Yup, i can convert it to string, but i would need the NSUUID to retrieve connection next time and so i would to convert the string back to NSUUID after i get from core data? – wes. i Jan 28 '16 at 10:12
  • @pbasdf Okay, i have tried with convert to string, store to Core data, then retrieve it from Core Data in string type then i use following code 'DeviceList.identifier[indexPath.row] = NSUUID(UUIDString: test)!' to convert to NSUUID but it fails, i can't figure out why – wes. i Jan 28 '16 at 11:04
  • What error message do you get? – pbasdf Jan 28 '16 at 11:19
  • hmm it could not unwrap string to NSUUID, but anyway i get it working with storing to attribute type "transformable"! Thanks anyway – wes. i Jan 29 '16 at 01:33

1 Answers1

3

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.

Mazyod
  • 22,319
  • 10
  • 92
  • 157
Tom Harrington
  • 69,312
  • 10
  • 146
  • 170
  • Yah it's working now, i just try to store with attribute type "transformable" and i got it works! Thank you very much! – wes. i Jan 29 '16 at 01:31