How to add the value of string into hashtable in iPhone coding?
for(NSString *s in mainarr)
{
NSString newseparator = @"=";
NSArray *subarray = [s componentsSeparatedByString : newseparator];
//Copying the elements of array into key and object string variables
NSString *key = [subarray objectAtIndex:0];
NSLog(@"%@",key);
NSString *class_name= [subarray objectAtIndex:1];
NSLog(@"%@",class_name);
//Putting the key and objects values into hashtable
NSDictionary *dict= [NSDictionary dictinaryWithObject:@"class_name" forKey:@"key"];
}
Hello.. in the above code i ve to parse the elements of array in a for loop, and then hav开发者_如何学编程e to put the substring key and class_name into a hashtable. how to put a value of those string variables into hashtable. in the code above i guess the variables class_name and key are put into hashtable not the value. i suppose its a wrong method. wat can be done to achieve the solution?
(1), You should write
NSString* newseparator = @"=";
although directly using
NSArray *subarray = [s componentsSeparatedByString:@"="];
is much better (or make newseparator
a global constant).
(2), Your last statement,
NSMutableDictionary = [NSDictionary dictinaryWithObject:@"class_name" forKey:@"key"];
is invalid because (a) NSMutableDictionary
is a type; (b) you are creating a dictionary, not a mutable dictionary; (c) you are creating it every time, and overwriting the previous ones; (d) you are creating the dictionary with the constant values @"class_name"
and keys @"key"
, which does not corresponds to the actual variables class_name
and key
.
To add the key-value pairs into 1 hash table, you should create the mutable dictionary at the beginning
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
and then in the loop, use -setObject:forKey:
to add it into the dictionary:
[dict setObject:class_name forKey:key];
To conclude, you should modify the code as
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for(NSString *s in mainarr) {
NSArray *subarray = [s componentsSeparatedByString:@"="];
// Get the elements of array into key and object string variables
NSString *key = [subarray objectAtIndex:0];
NSLog(@"%@",key);
NSString *class_name= [subarray objectAtIndex:1];
NSLog(@"%@",class_name);
//Putting the key and objects values into hashtable
[dict setObject:class_name forKey:key];
}
return dict;
精彩评论