6

結果として、次のものが必要です。

(

    "some_key" = {
        "another_key" = "another_value";
    };

);

そうするために、私はこのコードを持っていますが、うまくいきません:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"another_value", @"another_key", nil];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array setValue:dictionary forKey:@"some_key"];

何か案が?ありがとう!

4

5 に答える 5

16

あなたのエラーはここにあります:

NSMutableArray *array = [[NSMutableArray alloc] init];
[array setValue:dictionary forKey:@"some_key"];

------------^^^^^

これを配列に設定しています。

これを試してください:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"another_value", @"another_key", nil];
NSDictionary *outDict=[[NSDictionary alloc]initWithObjectsAndKeys:dictionary,@"some_key", nil];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:outDict, nil];

新しいリテラルでは:

NSDictionary *d=@{@"another_key":@"another_value"};
NSDictionary *c=@{@"some_key":d};
NSArray *array=@[c];

またはネストされた作成:

NSArray *array=@[@{@"some_key":@{@"another_key":@"another_value"}}];
于 2013-03-22T16:05:04.437 に答える
4

AnNSMutableArrayは通常、末尾にオブジェクトを追加するだけで構築できます。メソッドはaddObject:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"another_value", @"another_key", nil];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:dictionary];

一方、ディクショナリをキー (@"some_key") でアドレス指定する場合は、外側のコンテナもディクショナリにする必要があります。

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:@"another_value", @"another_key", nil];
NSMutableDictionary *outerDict = [NSMutableDictionary dictionary];
[outerDict setObject:dictionary forKey:@"some_key"];
于 2013-03-22T16:09:32.247 に答える
2

setValue:forKey:配列は(または)を使用せずsetObject:forKey:、配列は辞書のように結合的ではありません。

setValue:forKey:KVC(Key Value Coding)です。

辞書の辞書の配列が必要です(以下の疑似plist形式)

<array>
  <dict>
    <key>someKey</key>
    <dict>
      <key>someOtherKey</key>
      <string>someValue</string>
    </dict>
  </dict>
  <dict>
    <key>someKey</key>
    <dict>
      <key>someOtherKey</key>
      <string>someValue</string>
    </dict>
  </dict>
  <dict>
    <key>someKey</key>
    <dict>
      <key>someOtherKey</key>
      <string>someValue</string>
    </dict>
  </dict>
  <dict>
    <key>someKey</key>
    <dict>
      <key>someOtherKey</key>
      <string>someValue</string>
    </dict>
  </dict>
</array>

`

于 2013-03-22T16:19:37.940 に答える
2

このような構造を求めていると思います

NSDictionary *anotherKeyValueDictionary = 
 [[NSDictionary alloc] initWithObjectsAndKeys:@"another_value", 
                                              @"another_key", nil];
NSDictionary *someKeyValueDictionary = 
 [[NSDictionary alloc] initWithObjectsAndKeys:@"anotherKeyValueDictionary", 
                                              @"some_key", nil];
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:someKeyValueDictionary];
于 2013-03-22T16:20:24.340 に答える