objective-c NSMutable 字典添加对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1117126/
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
NSMutable Dictionary adding objects
提问by djt9000
Is there a more efficient way to add objects to an NSMutable Dictionary than simple iteration?
有没有比简单迭代更有效的方法将对象添加到 NSMutable 字典?
Example:
例子:
// Create the dictionary
NSMutableDictionary *myMutableDictionary = [NSMutableDictionary dictionary];
// Add the entries
[myMutableDictionary setObject:@"Stack Overflow" forKey:@"http://stackoverflow.com"];
[myMutableDictionary setObject:@"SlashDotOrg" forKey:@"http://www.slashdot.org"];
[myMutableDictionary setObject:@"Oracle" forKey:@"http://www.oracle.com"];
Just curious, I'm sure that this is the way it has to be done.
只是好奇,我确定这是必须完成的方式。
采纳答案by stefanB
If you have all the objects and keys beforehand you can initialize it using NSDictionary's:
如果您事先拥有所有对象和键,则可以使用 NSDictionary 对其进行初始化:
dictionaryWithObjects:forKeys:
Of course this will give you immutable dictionary not mutable. It depends on your usage which one you need, you can get a mutable copy from NSDictionary but it seems easier just to use your original code in that case:
当然,这会给你不可变的不可变字典。这取决于您的使用情况,您可以从 NSDictionary 获得一个可变副本,但在这种情况下使用原始代码似乎更容易:
NSDictionary * dic = [NSDictionary dictionaryWith....];
NSMutableDictionary * md = [dic mutableCopy];
... use md ...
[md release];
回答by Andrew Johnson
NSDictionary *entry = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithDouble:acceleration.x], @"x",
[NSNumber numberWithDouble:acceleration.y], @"y",
[NSNumber numberWithDouble:acceleration.z], @"z",
[NSDate date], @"date",
nil];
回答by Tiago Almeida
Allow me to add some information to people that are starting.
请允许我向即将开始的人添加一些信息。
It is possible to create a NSDictionarywith a more friendly syntax with objective-c literals:
可以NSDictionary使用objective-c文字创建一个更友好的语法:
NSDictionary *dict = @{
key1 : object1,
key2 : object2,
key3 : object3 };
回答by Jeremiah Radich
NSMutableDictionary *example = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@5,@"burgers",@3, @"milkShakes",nil];
The objects come before the keys.
对象出现在键之前。

