【问题标题】:Auto-incrementing a key in a NSMutableDictionary自动增加 NSMutableDictionary 中的键
【发布时间】:2012-11-02 00:45:48
【问题描述】:

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

我尝试过,但没有成功:

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

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

谢谢:)

【问题讨论】:

  • 你想做什么?您发布的代码创建一个数组,将一个值放入数组中,然后销毁该数组。这没有任何意义。
  • 你想要递增键还是递增值?
  • 你正在使用 NSMutableDictionary,如果你想要自动递增的索引.. 你需要使用 NSMutableArray 来代替。
  • 我想要这个:第 0 项索引:0 - 第 1 项索引:1 - 第 2 项索引:02 - ...

标签: iphone plist auto-increment nsmutabledictionary


【解决方案1】:

使用这个:

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

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

【讨论】:

  • 我有 index: 1 for each dictionary
  • 只创建一次 testAutoIndex 例如在界面中:
【解决方案2】:

如果你想创建一个包含 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];

【讨论】:

    猜你喜欢
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2010-12-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    相关资源
    最近更新 更多