Create multiple numbered variables based on a int

前端 未结 2 2103
Happy的楠姐
Happy的楠姐 2020-11-22 11:24

How would I create a number of NSDictionary variables using an array\'s count?

This is basically what I came up with, but I\'m not sure how to make this

2条回答
  •  半阙折子戏
    2020-11-22 12:13

    You need to create a mutable array, and then put the objects into the array. You can't create a variable with the same name as the contents of a string, as you have done. For example:

    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];
    

    Or if you want to pull them out of the list by name:

    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"];
    

    But the first way is likely the easiest.

提交回复
热议问题