4

NSDictionary配列のカウントを使用して多数の変数を作成するにはどうすればよいですか?

これは基本的に私が思いついたものですが、Objective-C 構文でこれを機能させる方法がわかりません。doesntContainAnotherですNSArray。の現在の値を使用する辞書の名前が必要ですloopInt

int *loopInt = 0;
while (doesntContainAnother.count <= loopInt) {

    NSMutableDictionary *[NSString stringWithFormat:@"loopDictionary%i", loopInt] = [[[NSMutableDictionary alloc] init] autorelease];
    [NSString stringWithFormat:@"loopDictionary%i", loopInt] = [NSDictionary dictionaryWithObject:[array1 objectAtIndex:loopInt] 
                                                 forKey:[array2 objectAtIndex:loopInt]];
    loopInt = loopInt + 1;
}
4

2 に答える 2

4

変更可能な配列を作成し、元の配列の数に達するまでループし、辞書を作成して、反復ごとに変更可能な配列に追加します。

コードは次のようになります。

NSMutableArray *dictionaries = [[NSMutableArray alloc] init];
for (int i = 0; i < doesntContainAnother.count; i++) {
    [dictionaries addObject:[NSMutableDictionary dictionaryWithObject:[array1 objectAtIndex:i] forKey:[array2 objectAtIndex:i]]];
}

名前の末尾に数字を付けて変数を作成するアプローチはアンチパターンであり、Objective-C では不可能です。これは配列と同等ですが、より不格好です。

于 2010-02-09T19:24:36.380 に答える
2

可変配列を作成してから、オブジェクトを配列に入れる必要があります。行ったように、文字列の内容と同じ名前の変数を作成することはできません。例えば:

NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:[doesntContainAnother count]];
int i = 0;    // Note: type is int, not int*
for (i = 0; i < [doesntCountainAnother count]; i++) {
    [arr addObject:[NSMutableDictionary dictionary]];
}

// Later...
NSMutableDictionary *d1 = [arr objectAtIndex:3];

または、名前でリストからそれらを引き出したい場合:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithCapacity:[doesntCountainAnother count]];
int i = 0;
for (i = 0; i < [doesntContainAnother count]; i++) {
    [dict setObject:[NSMutableDictionary dictionary] forKey:[NSString stringWithFormat:@"loopDictionary%d", i]];
}

// Later...
NSMutableDictionary *d1 = [dict objectForKey:@"loopDictionary3"];

しかし、最初の方法がおそらく最も簡単です。

于 2010-02-09T19:39:07.957 に答える