简体   繁体   中英

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     LENOVA
  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]];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM