What is the way to persist a trie data tree with 27000 nodes in iOS using Swift?

假装没事ソ 提交于 2019-12-11 07:35:07

问题


I am building a Trie tree that will have about 27000 of the nodes below. Instead of recreating it every time on app start, I would like to persist. Because the child property is a dictionary to another node, I'm having trouble using NSCoding to archive and store it in the core data entity. Is there a way to store this node in Core Data? Or should I be using a different type of persistence?

class TrieNode {

    var letter:Character
    var fullWord:Bool
    var leadingLetters:String
    var child = [Character:TrieNode]()

    init (letter:Character, leadingLetters:String, fullWord:Bool) {
        self.letter = letter
        self.fullWord = fullWord
        self.leadingLetters = leadingLetters
    }
}    

The main problem I had in trying to use Core Data is how to convert var child = [Character:TrieNode]() into NSData or another useable type that CD can store in an entity. Examples on how to do that would be appreciated.


回答1:


It's a little awkward in Core Data. I think what I'd do is:

  1. Create a new entity called something like TrieNodeLink. It has one property, a string called something like childString and one relationship, called node of type TrieNode. Each instance of this entity represents one single sub-node of a trie node.
  2. Add a new to-many relationship from your existing TrieNode to the new TrieNodeLink entity.
  3. Keep your existing child dictionary. At a convenient time, initialize this dictionary by scanning the new to-many relationship from step 2. A convenient time might be in awakeFromFetch, or else you could make it a Swift lazy property. Or if you want to pre-load data for faster performance at the cost of higher memory use, you might write some code to recursively load child nodes a few levels deep before they're needed.

The effect of this would be that you'd load portions of the trie on demand, when needed. Once loaded you'd be able to use your child dictionary to quickly look up child nodes.



来源:https://stackoverflow.com/questions/38553397/what-is-the-way-to-persist-a-trie-data-tree-with-27000-nodes-in-ios-using-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!