将NSMutableDictionary的键/值存储到另一个NSMutableDictionary

时间:2012-07-12 04:11:53

标签: objective-c ios nsmutabledictionary

所以我有三个这样的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;

(init)

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 

相关:

2 个答案:

答案 0 :(得分:2)

在数组中添加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];

答案 1 :(得分:1)

将数据添加到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代表世界和条形键的值类型。

继续..