如何在NSArray中加载txt文件?

时间:2013-02-18 21:17:43

标签: iphone objective-c

如何在NSArray中加载按行划分的txt文件的内容? 基本上,我有一个文件“count.txt”,其中我写了元素的数量(并且它起作用),“1t.txt”表示第一行的标题,“1.txt”表示内容。 我的意思是只是按值添加值。 然后,当用户点击表视图的标题时,我希望他读取“* .txt”的内容(如果我有数组文件的索引,那显然很容易)

现在我使用这段代码:

- (void) loadMainArray
{
    for (int i = 1; i <= max; i++)
    {
    NSString *currentNumber;
    currentNumber = [NSString stringWithFormat:@"%it", i];
    NSLog(@"%i° file read", i);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:currentNumber ofType:@"txt"];
    if ([fileManager fileExistsAtPath:dataFilePath])
    {
        NSString *content = [NSString stringWithContentsOfFile:dataFilePath encoding:NSUTF8StringEncoding error:nil];
        NSArray *parsed = [content componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
        mainArray = (__bridge NSMutableArray*)CFPropertyListCreateDeepCopy(kCFAllocatorDefault, (CFPropertyListRef)parsed, kCFPropertyListMutableContainers);
        NSLog(@"%@", parsed);

    }
    else{
    }
    }
}

(对不起,如果代码没有对齐,但我在stackoverflow中无法做到这么多) 无论如何,在ViewLoad中调用此方法后,我得到Signal SIGABRT,我错了?

N.B:也设置了max,我在NSLog中检查过。 mainArray是一个NSMutableArray。

1 个答案:

答案 0 :(得分:5)

你想要的是

-(NSArray *)componentsSeparatedByString:(NSString *)separator;

将在指定的分隔符处分割字符串。所以基本上你这样做:

NSArray *parsed = [content componentsSeparatedByString:@"\n"];
//assuming you want a newLine as a separator

现在你继续做你的事。 玩得开心

编辑:

我不确定你的可变数组桥是否正确。 您似乎应该使用NSData-Object来捕获您对

的调用的返回值
CFPropertyListCreateDeepCopy

如果有需要,您可以随后将其转换为MutableArray。 这也解释了您的SIGABRT错误。