问题
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:
- Create a new entity called something like
TrieNodeLink
. It has one property, a string called something likechildString
and one relationship, callednode
of typeTrieNode
. Each instance of this entity represents one single sub-node of a trie node. - Add a new to-many relationship from your existing
TrieNode
to the newTrieNodeLink
entity. - 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 inawakeFromFetch
, or else you could make it a Swiftlazy
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