开发者

Contents of file as input to hashtable in Objective-C

I know to read the contents of file in Objective-C, but how to take it as the input to hashtable. Consider the contents of text file as test.txt

LENOVA 
HCL 
WIPRO 
DELL

Now i need to read this into my Hashtable as Key value pairs

KEY   VAlue

  1     LENOV开发者_如何转开发A
  2     HCL
  3     WIPRO
  4     DELL


You want to parse your file into an array of strings and assign each element in this array with a key. This may help you get in the right direction.


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++;
    }
}

Keep in mind this isn't the most efficient method of parsing your file. It also uses the deprecated method stringWithContentsOfFile:.

To get the line back, use:

NSString *myLine = [dict objectForKey:@"1"];

// If you used `NSNumber` class for keys, use:
// NSString *myLine = [dict objectForKey:[NSNumber numberWithInt:1]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜