iPhone编码中如何将字符串的值添加到哈希表中?
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 循环中解析数组的元素,然后必须将子字符串键和 class_name 放入哈希表中。如何将这些字符串变量的值放入哈希表中。 在上面的代码中,我猜变量 class_name 和 key 被放入哈希表中,而不是值。我想这是一个错误的方法。可以做什么来实现解决方案?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
但您应该编写。
(1),尽管直接使用
要好得多(或将
newseparator
设为全局常量),(2),您的最后一条语句
无效,因为 (a) NSMutableDictionary 是一种类型; (b) 您正在创建字典,而不是可变字典; (c) 您每次都创建它,并覆盖以前的; (d) 您正在使用常量值
@"class_name"
和键@"key"
创建字典,该字典与实际变量class_name< /code> 和
key
。要将键值对添加到 1 个哈希表中,您应该在开头创建可变字典
,然后在循环中使用
-setObject:forKey:
将其添加到字典中:总而言之,你应该将代码修改为
(1), You should write
although directly using
is much better (or make
newseparator
a global constant).(2), Your last statement,
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 variablesclass_name
andkey
.To add the key-value pairs into 1 hash table, you should create the mutable dictionary at the beginning
and then in the loop, use
-setObject:forKey:
to add it into the dictionary:To conclude, you should modify the code as