0

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

有关的:

4

2 回答 2

2

Add your myD1 myD2 dictionaries in an Array and set it to the myContainer dictionary as below :

NSMutableArray *array = [NSMutableArray arrayWithObjects:myD1, myD2, nil];
[myContainer setObject:array forKey:@"common_index"];

And for retreiving them :

NSMutableDictionary *myD1Retrieved = [[myContainer objectForKey:@"common_index"] objectAtIndex:0];
NSMutableDictionary *myD2Retrieved = [[myContainer objectForKey:@"common_index"] objectAtIndex:1];
于 2012-07-12T04:54:08.673 回答
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代表世界和酒吧键的值类型。

继续..

于 2012-07-12T04:35:22.283 回答