我正在开发一个基于单词的游戏,我需要将我的 180,000 单词词典 (1.9MB) 加载到一个数组中,以便求解算法可以使用它。字典只是每行一个单词,像这样:
a
ab
abs
absolutely
etc
...
现在我正在使用以下代码将该文件加载到数组中:
NSString *txtPath = [[NSBundle mainBundle] pathForResource"dict" ofType"txt"];
NSString *stringFromFile = [[NSString alloc]
initWithContentsOfFile:txtPath
encoding:NSUTF8StringEncoding
error:&error ];
for (NSString *word in [stringFromFile componentsSeparatedByString"\r\n"]) {
[wordsArray addObject:word];
}
这在 iPhone 4 上大约需要 3-4 秒。在较旧的 iOS 设备上可能会更慢。有没有更快的方法来做到这一点?
Best Answer-推荐答案 strong>
您可以使用 Grand Central Dispatch 或 GCD 在后台轻松执行此操作,离开主线程。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0),^(void){
NSString *txtPath = [[NSBundle mainBundle] pathForResource"dict" ofType"txt"];
NSString *stringFromFile = [[NSString alloc]
initWithContentsOfFile:txtPath
encoding:NSUTF8StringEncoding
error:&error ];
for (NSString *word in [stringFromFile componentsSeparatedByString"\r\n"]) {
[wordsArray addObject:word];
}
});
I wrote the enclosing dispatch code from memory, but it's close (if not correct) and I think you get the idea.
EDIT: You can execute this code on the main thread, but what happens is a non-main-thread dispatch queue is where your code executes, thereby NOT blocking the UI.
You can improve the performance of your code here a little bit by replacing the for loop with just this:
[wordsArray setArray:[stringFromFile componentsSeparatedByString"\r\n"]];
应该不需要迭代 -componentsSeparatedByString: (一个数组)的结果,只是将它们放入 another 数组中。有了 180K 字,这应该可以节省大量时间。
关于objective-c - 将单词列表字典加载到数组中的最快方法?,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/10146171/
|