-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"];
 }    

你好.. 在上面的代码中,我已经在 for 循环中解析数组的元素,然后必须将子字符串 key 和 class_name 放入哈希表中。如何将这些字符串变量的值放入哈希表中。在上面的代码中,我猜变量 class_name 和 key 被放入哈希表而不是值。我想这是一个错误的方法。可以做些什么来实现解决方案?

4

1 回答 1

2

(1), 你应该写

 NSString* newseparator = @"=";

虽然直接使用

 NSArray *subarray = [s componentsSeparatedByString:@"="]; 

好多了(或者做newseparator一个全局常量)。


(2),你的最后一句话,

    NSMutableDictionary = [NSDictionary dictinaryWithObject:@"class_name" forKey:@"key"];

无效,因为 (a)NSMutableDictionary是一种类型;(b) 您正在创建字典,而不是可变字典;(c) 你每次都在创建它,并覆盖以前的;(d) 您正在使用常量值@"class_name"和键创建字典,这与实际变量和@"key"不对应。class_namekey

要将键值对添加到 1 个哈希表中,您应该在开始时创建可变字典

NSMutableDictionary* dict = [NSMutableDictionary dictionary];

然后在循环中,使用-setObject:forKey:将其添加到字典中:

[dict setObject:class_name forKey:key];

最后,您应该将代码修改为

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;
于 2010-02-08T08:56:27.337 回答