Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing UUIDs in Core Data

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!

like image 376
Michael Waterfall Avatar asked Mar 22 '11 14:03

Michael Waterfall


People also ask

What is UUID core data?

A universally unique value to identify types, interfaces, and other items. iOS 6.0+ iPadOS 6.0+ macOS 10.8+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Xcode 8.0+

How do you make a core data attribute unique with constraints?

If you look in the Data Model inspector you'll see a field marked "Constraints" – click the + button at the bottom of that field. A new row will appear saying "comma,separated,properties". Click on that, hit Enter to make it editable, then type "sha" and hit Enter again. Make sure you press Cmd+S to save your changes!


2 Answers

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
}
like image 156
Jonny Avatar answered Oct 21 '22 12:10

Jonny


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.

like image 43
Caleb Avatar answered Oct 21 '22 11:10

Caleb