0

我想自动增加一个键和一个 NSMutableDictionary。

我试图这样做,但它不起作用:

NSMutableDictionary *array = [[NSMutableDictionary alloc] init];

int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:testAutoIndex++] forKey:@"index"];
[array release];

谢谢 :)

4

2 回答 2

0

用这个:

NSMutableDictionary *array = [[NSMutableDictionary alloc] init];

int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:++testAutoIndex] forKey:@"index"];
[array release];
于 2012-11-02T00:58:26.940 回答
0

如果你想创建一个包含 N 个条目的字典,那么可以使用代码

int N = 100; // or what ever number you want
NSArray *arrayOfObjectsYouWantToPumpIntoDictionary = ....;
NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithCapacity:100];

for(int i=0;i<N;i++){

    NSString *key = [NSString stringWithFormat:@"%d"i];
    [mutableDictionary setObject:[arrayOfObjectsYouWantToPumpIntoDictionary objectAtIndex:i] forKey:];
}

// Later some where else if you want to retrieve object with key of x (x can be 1, or 2 or what ever value), you can do

 objectToBeRetrieved = [mutableDictionary objectForKey:[NSString stringWithFormat:@"%d",x];
于 2012-11-02T21:20:46.007 回答