如何从objective-c中的文件中读取值列表?

时间:2012-07-20 14:23:31

标签: objective-c cocoa file-handling

我有一个这种格式的文件值列表:

#number of items#
#item type#value x#value y#
#...

示例:

#100#
#1#150#200#
#1#250#200#
#2#350#200#
#2#450#250#
#1#550#350#
#...

想将此读入代码......

1 个答案:

答案 0 :(得分:1)

你可以做这样的事情,但不知道性能

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"file" ofType:@"txt"];
NSString *fileContent = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

NSArray *lines = [fileContent componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

if (lines.count > 1)
{
    NSString *firstLine = [lines objectAtIndex:0];
    NSCharacterSet *seperatorSet = [NSCharacterSet characterSetWithCharactersInString:@"#"];

    int itemCount = [[firstLine stringByTrimmingCharactersInSet:seperatorSet] intValue];

    for (int i = 1; i < lines.count; ++i)
    {
        NSString *line = [lines objectAtIndex:i];
        NSArray  *components = [line componentsSeparatedByCharactersInSet:seperatorSet];

        //starts at 1 because first and last are empty strings
        int type = [[components objectAtIndex:1] intValue];
        int x    = [[components objectAtIndex:2] intValue];
        int y    = [[components objectAtIndex:3] intValue];
    }
}