views:

226

answers:

1

Hello,

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
A: 

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]];
dreamlax
`stringWithContentsOfFile:` is deprecated in favour of `stringWithContentsOfFile:usedEncoding:error:` which gives you information about what encoding was detected when reading the file and also returns an `NSError` object when there was a failure reading the file.
dreamlax
hey.. this is how we check the contents of hashtable right?? " NSLog(@"1=%@",[dict objectForKey:@"1"]); "
suse
@suse, not quite, in the above I have used `NSNumber` class as the key, but in your comment you are trying to use `NSString` as the key. If you want `NSString` as the key, you need to change the `setObject:forKey:` part. I have edited my answer to assist you further.
dreamlax
wat should i write for the value of "i", its giving me an error saying 'i' is undeclared, first use inthis function?? Its the key value right? but how to declare it?
suse
Oops! Sorry, that is a typo, `i` is meant to read `counter`. My mistake. Please try again.
dreamlax