将 NSMutableDictionary 的键/值存储到另一个 NSMutableDictionary
Posted
技术标签:
【中文标题】将 NSMutableDictionary 的键/值存储到另一个 NSMutableDictionary【英文标题】:Store key / value of NSMutableDictionary to another NSMutableDictionary 【发布时间】:2012-07-12 04:11:52 【问题描述】:所以我有三个这样的 NSMutableDictionary:
.h 文件
NSMutableDictionary *myContainer;
NSMutableDictionary *myD1;
NSMutableDictionary *myD2;
@property (nonatomic, retain) NSMutableDictionary *myContainer;
@property (nonatomic, retain) NSMutableDictionary *myD1;
@property (nonatomic, retain) NSMutableDictionary *myD2;
.m 文件
@synthesize myContainer;
@synthesize myD1;
@synthesize myD2;
(初始化)
self.myContainer = [[NSMutableDictionary alloc] init];
self.myD1 = [[NSMutableDictionary alloc] init];
self.myD2 = [[NSMutableDictionary alloc] init];
现在我想将字典中的值或位置从 myD1 和 myD2 添加到 myContainer
伪:
[myD1 setValue:foo forKey:@"bar"];
[foo retain];
[myD2 setValue:hello forKey:@"world"];
[hello retain];
所以我的问题是如何将特定的键/值添加到 myD1 和/或 myD2 到 myContainer?然后也从它们中检索键/值?
下面看起来像我需要的,但我是新手,我的格式不同。
来自 php 的我将如何构建它:
$myContainer = array();
$myD1 = array();
$myd2 = array();
$myD1['bar'] = 'foo';
$myD2['world'] = 'hello';
$myContainer['common_index'] = array($myD1, $myD2);
// Alternative
//$myContainer['common_index'] = array(0 => $myD1, 1 => $myD2);
// Retrieving values from $myD1
echo "Value: ".$myContainer['common_index'][0]['bar']."\n";
echo "Value: ".$myContainer['common_index'][1]['world']."\n";
// Alternative
foreach($myContainer['common_index'] as $array)
foreach($array as $index => $value)
echo "Index: $index Value: $value \n";
输出:
Value: foo
Value: hello
Index: bar Value: foo
Index: world Value: hello
相关:
NSMutableDictionary with single key holding many values in Objective-C programming【问题讨论】:
【参考方案1】:将您的 myD1 myD2 字典添加到数组中并将其设置为 myContainer 字典,如下所示:
NSMutableArray *array = [NSMutableArray arrayWithObjects:myD1, myD2, nil];
[myContainer setObject:array forKey:@"common_index"];
为了找回它们:
NSMutableDictionary *myD1Retrieved = [[myContainer objectForKey:@"common_index"] objectAtIndex:0];
NSMutableDictionary *myD2Retrieved = [[myContainer objectForKey:@"common_index"] objectAtIndex:1];
【讨论】:
【参考方案2】:向 myContainer 添加数据:
[myContainer setValue:[mD1 valueForKey:@"bar"] forKey:@"bar"];
[myContainer setValue:[mD2 valueForKey:@"world"] forKey:@"world"];
用于从 myContainer 中检索:
Object *firstObject = [myContainer valueForKey:@"world"];
Object *secondObject = [myContainer valueForKey:@"bar"];
Object
代表世界和条形键的值类型。
继续..
【讨论】:
以上是关于将 NSMutableDictionary 的键/值存储到另一个 NSMutableDictionary的主要内容,如果未能解决你的问题,请参考以下文章
NSMutableDictionary 实例变量不保留循环外的键值
使用 UIImageView 作为 NSMutableDictionary 中的键来查找布尔值
如何使用键将对象添加到 NSMutableDictionary?
NSInvalidArgumentException/copyWithZone 异常与 NSMutableDictionary