【发布时间】:2011-05-16 05:06:10
【问题描述】:
我想在现有字典中插入一个具有相应值的键...
我可以为字典中的现有键设置值,但我无法添加新键值...
任何帮助将不胜感激。
【问题讨论】:
标签: iphone key nsmutabledictionary
我想在现有字典中插入一个具有相应值的键...
我可以为字典中的现有键设置值,但我无法添加新键值...
任何帮助将不胜感激。
【问题讨论】:
标签: iphone key nsmutabledictionary
使用 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"
【讨论】:
yourNSDictionary = yourMutableDictionary as NSDictionary 一样转换它。
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
通过使用这种方法,我们可以将新值添加到 NSMutableDictionary
[dict setObject:@"Value" forKey:@"Key"];
要知道字典中是否存在键
[[dict allKeys] containsObject:@"key"];
【讨论】:
您好,我从 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];
}];
【讨论】:
NSDictionnary 是不可变的。请改用 NSMuteableDictory。
adding 对象:setObject:forKey:
测试密钥是否存在:
[[aDict allKeys] containsObject:@"key"];
【讨论】: