views:

235

answers:

1
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 have 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?

+2  A: 

(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;
KennyTM
Thanks a lots.. it worked :)
suse
Can i put the object with key into hashtable?if myClass *obj = [[myClass alloc]init];, can i write like this. [dict setObject:obj forKey:key];
suse
@suse: Yes. You can put any ObjC object into as the value of the dictionary.
KennyTM
@kenny, is the syntax same for loading instance and loading a string into Hashtable? .......................... [dict setObject:object forKey:key];
suse
@suse: Yes. :::
KennyTM