Storing UUIDs in Core Data

12,645

Solution 1

How many of these are you planning on storing? Storing them as binary data saves about 50% -- roughly 20 bytes as binary data vs. roughly 40 bytes as a string. So you're talking about saving a whole 20K per thousand UUID's, which isn't so much that I'd worry about it either way. However, if you really want to save them as binary data, you can do that by storing them as NSData objects.

Solution 2

Starting at iOS 11, you can set UUID attribute directly in Core Data editor. UUID will be stored as binary automatically.

enter image description here

You can then fetch your Core Data objects using UUID (in Obj-C, NSUUID).

static func fetch(with identifier: UUID) -> AudioRecord? {
    var record: AudioRecord?
    moc.performAndWait {
        let fetchRequest = AudioRecord.request
        fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier as CVarArg)
        fetchRequest.fetchLimit = 1
        record = (try? fetchRequest.execute())?.first
    }
    return record
}
Share:
12,645

Related videos on Youtube

Michael Waterfall
Author by

Michael Waterfall

Updated on May 25, 2022

Comments

  • Michael Waterfall
    Michael Waterfall over 1 year

    What is the best method for storing UUIDs (for global multi-system object identification) in Core Data? Taking into account storage size and indexing capabilities.

    Ideally it would be stored as binary data (in 128-bits), but are there any immediate problems with doing this? It would be more efficient size-wise storing it this way rather than as an NSString, but I just want to check that there's no performance issues with storing this as binary data. Will it still be properly indexed as binary data? Are there any disadvantages storing what is effectively fixed-width binary data in a variable width field?

    I'm not overly familiar with SQLite and it's storage/indexing mechanisms so wanted to reach out for some advice!

  • Michael Waterfall
    Michael Waterfall over 12 years
    Do you know if the "binary data" fields are properly indexable?
  • Caleb
    Caleb over 12 years
    Did you set the "Indexed" flag for that attribute in your model?
  • Michael Waterfall
    Michael Waterfall over 12 years
    Yes that's ticked. I'm just wondering about any internal problems or things I should know about with storing and indexing small blobs.
  • bentford
    bentford over 9 years
    I usually save them as NSStrings. This makes viewing and writing queries pretty straightforward. I never had any problems disk size.