Home > database >  Best way to read a single keyValue from a dictionary that's stored on disk
Best way to read a single keyValue from a dictionary that's stored on disk

Time:06-11

I have a dictionary of type [String: [MyObject]] like this:

[
  "aKey": [MyObject, MyObject...],
  "anotherKey": [MyObject...]
]

I store this on the disk. Each key will contain a lot of data in its value. I want the ability to both retrieve the whole dictionary, and retrieve the value of a single key without having to retrieve the whole dictionary from disk. Is this possible?

I currently write and read my dictionary like so:

func write(
  _ value: [String: [MyObject]],
  forKey: String
) {
  let data = NSKeyedArchiver.archivedData(withRootObject: value)
  writeDataToDisk(data: data, key: key)
}

func read(
  _ key: String
) -> [String: [MyObject]]? {
  guard let dataFromDisk = fileManager.contents(atPath: cachePath(forKey: key)) else {
    return nil
  }
  guard let data = NSKeyedUnarchiver.unarchiveObject(with: data) as? Data else {
    return nil
  }
  do {
    return try JSONDecoder().decode([String: [MyObject]].self, from: data)
  } catch {
    return nil
  }
}

CodePudding user response:

Joakim already gave you a fairly complete answer as a comment, but I'll flesh it out a little as an answer.

Most of the methods for serializing/deserializing dictionaries to disk read and write the entire dictionary.

NSKeyedArchiver, Codable, JSONSerialization, plist - they all deal with an entire object graph.

If you want to read/write single objects using one of these methods you'll have to save each object to a separate file.

Alternatively, use a database to store your objects. Core Data, SQLite, and various others are possibilities.

  • Related