代码之家  ›  专栏  ›  技术社区  ›  suse

objective-c中作为哈希表输入的文件内容

  •  1
  • suse  · 技术社区  · 16 年前

    我知道在objective-c中读取文件的内容,但如何将其作为hashtable的输入。 将文本文件的内容视为test.txt

    LENOVA 
    HCL 
    WIPRO 
    DELL
    

    现在我需要将其作为键值对读入哈希表

    KEY   VAlue
    
      1     LENOVA
      2     HCL
      3     WIPRO
      4     DELL
    
    1 回复  |  直到 16 年前
        1
  •  0
  •   dreamlax    16 年前

    您需要将文件解析为一个字符串数组,并用一个键分配该数组中的每个元素。这也许能帮你找到正确的方向。

    
    NSString *wholeFile = [NSString stringWithContentsOfFile:@"filename.txt"];
    NSArray *lines = [wholeFile componentsSeparatedByString:@"\n"];
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[lines count]];
    int counter = 1;
    
    for (NSString *line in lines)
    {
        if ([line length])
        {
            [dict setObject:line forKey:[NSString stringWithFormat:"%d", counter]];
    
    //      If you want `NSNumber` as keys, use this line instead:
    //      [dict setObject:line forKey:[NSNumber numberWithInt:counter]];
    
            counter++;
        }
    }

    请记住,这不是解析文件的最有效方法。它还使用不推荐的方法 stringWithContentsOfFile: .

    要恢复线路,请使用:

    NSString *myLine = [dict objectForKey:@"1"];
    
    // If you used `NSNumber` class for keys, use:
    // NSString *myLine = [dict objectForKey:[NSNumber numberWithInt:1]];
    
    推荐文章