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开发者_Go百科 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!
Starting at iOS 11, you can set UUID attribute directly in Core Data editor. UUID will be stored as binary automatically.
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
}
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.
I store my UUID as "Transformable" and it works well.
Add this to your
NSManagedObject
subclass:@NSManaged var uuid: NSUUID!
in your core data model (.xcdatamodel file), create an attribute with name
uuid
with TypeTransformable
Querying works well too, I write my predicates to search on them like this:
request.predicate = NSPredicate(format: "uuid == %@", withUuid)
精彩评论