如何格式化要使用arrayWithContentsOfFile读取的文本文件 [英] How do I format a text file to be read in using arrayWithContentsOfFile
问题描述
我有几个大单词列表,并且已经在代码中按如下方式将它们加载到位:
I have several large word lists and I had been loading them in place in the code as follows:
NSArray *dict3 = [[NSArray alloc] initWithObjects:@"abled",@"about",@"above",@"absurd",@"absurdity", ...
但是现在它实际上正在奇怪地引起一个exc_bad_access错误,我知道这似乎是不可行的,但是由于某种原因它正在引起它. (相信我,我只是花了一天的大部分时间调试这种废话)
but now it is actually causing an exc_bad_access error weirdly, i know it seems implausible but for some reason IT IS causing it. (trust me on this I just spend the better part of a day debugging this crap)
无论如何,我希望从文件中删除这些繁琐的代码行,但是我不确定最好的方法是什么.我想我可以做一个plist,但是我需要弄清楚如何自动执行该过程.
Anyway, I'm looking to get these humongous lines of code out of my files but I'm not sure what the best approach is. I guess I could do a plist but I need to figure out how to automate the process.
最简单的方法是只使用我一直在编译的文本文件,以便有人知道如何格式化文本文件,以便
it be easiest if I could just use the text files I've been compiling so if anyone knows how I can format the text file so that the
myArray = [NSArray arrayWithContentsOfFile: @"myTextFile.txt"];
将正确地读入数组中的每个元素一个单词,这将是不胜感激的.
will be read in correctly as one word per element in the array it would really be appreciated.
推荐答案
我最终通过一个朋友代码进行清理,找到了答案,实际上是一小段代码:
I ended up scavenging through a friends code and found my answer, nice little piece of code actually:
- (NSArray *) readFile:(NSString *) path {
NSString *file = [NSString stringWithContentsOfFile:path];
NSMutableArray *dict = [[NSMutableArray alloc] init];
NSCharacterSet *cs = [NSCharacterSet newlineCharacterSet];
NSScanner *scanner = [NSScanner scannerWithString:file];
NSString *line;
while(![scanner isAtEnd]) {
if([scanner scanUpToCharactersFromSet:cs intoString:&line]) {
NSString *copy = [NSString stringWithString:line];
[dict addObject:copy];
}
}
NSArray *newArray = [[NSArray alloc] initWithArray:dict];
return newArray;
}
这篇关于如何格式化要使用arrayWithContentsOfFile读取的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!