我想自动增加一个键和一个 NSMutableDictionary。
我试图这样做,但它不起作用:
NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:testAutoIndex++] forKey:@"index"];
[array release];
谢谢 :)
我想自动增加一个键和一个 NSMutableDictionary。
我试图这样做,但它不起作用:
NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:testAutoIndex++] forKey:@"index"];
[array release];
谢谢 :)
用这个:
NSMutableDictionary *array = [[NSMutableDictionary alloc] init];
int testAutoIndex = 0;
[array setObject:[NSNumber numberWithInt:++testAutoIndex] forKey:@"index"];
[array release];
如果你想创建一个包含 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];