ios 如何在 NSDictionary 中添加字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11209964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:58:43  来源:igfitidea点击:

How to add a string in a NSDictionary?

objective-cios

提问by Alexis

Possible Duplicate:
How to add to an NSDictionary

可能的重复:
如何添加到 NSDictionary

When I do that :

当我这样做时:

NSDictionary *dic = [NSDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];

my app just crash. I don't understand why. How should I add a string in a dictionary ?

我的应用程序崩溃了。我不明白为什么。我应该如何在字典中添加字符串?

回答by dasblinkenlight

You need to make your dictionary mutable, otherwise it would not respond to the setValue:forKey:selector:

你需要让你的字典mutable,否则它不会响应setValue:forKey:选择器:

NSMutableDictionary *dic = [NSMutableDictionary dictionary];

This is a common pattern in cocoa: you often see classes declared in pairs: NSArray/NSMutableArray, NSSet/NSMutableSet, NSString/NSMutableString, and so on. Mutable version is capable of doing everything that the immutable version can do, but it also supports operations that change its content.

这是可可中的常见模式:您经常看到成对声明的类:NSArray/ NSMutableArrayNSSet/ NSMutableSetNSString/NSMutableString等等。可变版本能够做不可变版本可以做的所有事情,但它也支持改变其内容的操作。

回答by janusfidel

NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];    

or

或者

NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"nvjd",@"name" nil];

回答by Alladinian

You have two options. Either you initialize your NSDictionarywith a key/value pair (or more than one), or create an NSMutableDictionaryand add it later.

你有两个选择。要么NSDictionary使用键/值对(或多个)初始化,要么创建一个NSMutableDictionary并稍后添加。

// Immutable
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"nvjd" forKey:@"name"];

// Mutable
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:@"nvjd" forKey:@"name"];