【问题标题】:Recover the value in an NSDictionary恢复 NSDictionary 中的值
【发布时间】:2011-05-06 13:43:49
【问题描述】:

我想恢复 NSDictionary 中包含的值。 我这样做:

MyCommon *pCommon = [MyCommon Singleton];
NSArray *result = pCommon.res; //res is define and retain in common.m. This is the array.
NSDictionary *dataItem = [result objectAtIndex:????];

我不知道我可以用什么来代替 ????

谢谢

【问题讨论】:

  • 你的字典在什么索引?
  • result 是 NSDictionary 的数组吗?
  • 需要更多信息?很难看到你在这里想要完成什么。 objectAtIndex 采用 NSUInteger 值。
  • 您的问题是如何在 NSDictionnary 中检索值,但您的代码从 NSArray 中检索值(NSDictionary)?哪一个是正确的“问题”?

标签: objective-c


【解决方案1】:

与其他一些语言不同,Objective-C 区分数组和字典。

数组是一个集合,按数字索引。字典是由对象(通常是字符串,但也可以是其他类型)索引的集合。

最重要的是,Objective-C 区分了可变和不可变数组和字典。 NSArrayNSDictionary 创建后无法修改。如果您需要将对象添加到您的集合中,请改用NSMutableArrayNSMutableDictionary

NSArray * myArray = [[NSArray alloc] initWithObjects: @"text1", @"text2", @"text3", nil];
// you can then access a member by using:
NSString * text = [myArray objectAtIndex: 0];

NSMutableDictionary * myDict = [[NSMutableDictionary alloc] init];
// add an object
[myDict setObject:@"text1" forKey:@"key1"];
[myDict setObject:@"text2" forKey:@"key2"];
// you can retrieve objects using:
text = [myDict objectForKey: @"key1"];

[myArray release];
[myDict release];

【讨论】:

    【解决方案2】:

    好吧,resultNSArray,而不是 NSDictionary,所以只需输入您感兴趣的元素的索引即可。数组由从零开始的整数索引。

    如果您的resultNSDictionary 而不是NSArray,请使用objectForKey: 方法而不是objectAtIndex:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多