使用Swift在iOS中将带有27000个节点的特里数据树持久化的方法是什么? [英] What is the way to persist a trie data tree with 27000 nodes in iOS using Swift?

查看:91
本文介绍了使用Swift在iOS中将带有27000个节点的特里数据树持久化的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个Trie树,该树将包含下面的大约27000个节点.我不想坚持每次启动应用程序时都重新创建它.因为child属性是另一个节点的字典,所以在使用NSCoding将其归档并存储在核心数据实体中时遇到了麻烦.有没有办法将此节点存储在Core Data中?还是应该使用其他类型的持久性?

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
    }
}    

我在尝试使用Core Data时遇到的主要问题是如何将var child = [Character:TrieNode]()转换为CD可以存储在实体中的NSData或其他可用类型.有关如何执行此操作的示例将不胜感激.

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.

推荐答案

Core Data有点尴尬.我想我要做的是:

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

  1. 创建一个名为TrieNodeLink之类的新实体.它具有一个属性,一个名为childString的字符串,以及一个名为TrieNode类型的名为node的关系.该实体的每个实例代表一个Trie节点的一个单个子节点.
  2. 从现有的TrieNode到新的TrieNodeLink实体中添加新的多对多关系.
  3. 保留现有的child词典.在方便的时候,通过扫描步骤2中的新的多对多关系来初始化此词典.方便的时间可能在awakeFromFetch中,否则您可以将其设置为Swift lazy属性.或者,如果您想以更高的内存使用为代价来预加载数据以提高性能,则可以编写一些代码以在需要之前递归地将子节点加载几级.
  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.

这样做的结果是,您将在需要时按需加载部分Trie.加载后,您将可以使用child词典快速查找子节点.

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.

这篇关于使用Swift在iOS中将带有27000个节点的特里数据树持久化的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆