我想在现有词典中插入具有相应值的键...
我能够为字典中的现有键设置值,但我无法添加新的键值......
任何帮助都将不胜感激。
答案 0 :(得分:50)
使用NSMutableDictionary
NSMutableDictionary *yourMutableDictionary = [NSMutableDictionary alloc] init];
[yourMutableDictionary setObject:@"Value" forKey:@"your key"];
更新Swift:
以下是上述代码的确切swift副本
var yourMutableDictionary = NSMutableDictionary()
yourMutableDictionary.setObject("Value", forKey: "Key")
但我建议你使用Swift Dictionary方式。
var yourMutableDictionary = [String: AnyObject]() //Open close bracket represents initialization
//The reason for AnyObject is a dictionary's value can be String or
//Array or Dictionary so it is generically written as AnyObject
yourMutableDictionary["Key"] = "Value"
答案 1 :(得分:2)
NSDictionnary是不可变的。请改用NSMuteableDictiory。
adding对象:setObject:forKey:
测试密钥是否存在:
[[aDict allKeys] containsObject:@"key"];
答案 2 :(得分:2)
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
通过使用此方法,我们可以将新值添加到NSMutableDictionary
[dict setObject:@"Value" forKey:@"Key"];
知道字典中存在密钥
[[dict allKeys] containsObject:@"key"];
答案 3 :(得分:1)
您好我以字典的格式从json获取内容,并且我将内容添加到其他字典中
//here contract is my json dictionary
NSArray *projectDBList =[contract allKeys];//listing all the keys in dict
NSMutableDictionary *projectsList=[[NSMutableDictionary alloc]init];
[projectDBList enumerateObjectsUsingBlock:^(NSString * obj, NSUInteger idx, BOOL *stop) {
[projectsList setObject:[contract objectForKey:obj] forKey:obj];
}];