iPhone,如何存储值和键以及按键和索引查找?

时间:2010-11-04 19:35:21

标签: objective-c xcode uitableview

我尝试过NSMutableDictionary但是我似乎无法通过索引获取对象。

有什么想法吗?

编辑: 我试图创建一个uitableview部分对象,它将存储标题标题并能够增加行的计数器。我需要能够通过索引获得计数器,按标题值计算值。

3 个答案:

答案 0 :(得分:1)

不订购词典;因此,它们中的对象没有索引。

http://developer.apple.com/library/ios/#documentation/cocoa/reference/foundation/Classes/NSDictionary_Class/Reference/Reference.html#//apple_ref/occ/cl/NSDictionary

您需要使用密钥从字典中检索特定对象。如果您需要按特定顺序拥有对象,那么您可能会使用NSArray。

更新

在你的编辑中,你没有显示tableSectionArray是什么,但它看起来像是一个字典(这使得命名很差)。您应该使用NSArray而不是NSDictionary来存储您想要的内容。如果需要存储多个值,则存储包含所需值的对象。创建一个具有所需值作为属性的类;或者,如果合适,将NSDictionary对象添加到您的数组中。 (根据您尝试从tableSectionArray分配元素的方式,看起来您确实希望它包含字典。)但是您需要tableSectionArray本身作为NSArray。

答案 1 :(得分:1)

最简单的方法是使用2个集合:部分信息的字典(行号,国家等)和部分标题的数组。

NSMutableDictionary *sectionInfos;
NSMutableArray *sectionTitles;

当你需要截面信息时的部分信息:

NSDictionary *info = [sectionInfos objectForKey:sectionTitle];
int rowsCount = ((NSArray *)[info objectForKey:@"Countries"]).count;

当您需要sectionIndex:

的部分信息时
NSString *title = [sectionTitles objectAtIndex:sectionIndex];
NSDictionary *info = [sectionInfos objectForKey:title];
int rowsCount = ((NSArray *)[info objectForKey:@"Countries"]).count;

添加部分时,请添加部分信息:

[sectionInfos setObject:info forKey:sectionTitle];

和数组的标题,因此信息和标题将同步。

[sectionTitles addObject:sectionTitle];

更新:如果部分所需的唯一信息是行数: UPDATE2:添加类型。

NSMutableDictionary *sectionRowCounts;
NSMutableArray *sectionTitles;

按行数计算行数:

int rowCount = [[sectionRowCounts objectForKey:sectionTitle] intValue];

行数按sectionIndex计算:

NSString *title = [sectionTitles objectAtIndex:sectionIndex];
int rowCount = [[sectionRowCounts objectForKey:title] intValue];

添加部分:

[sectionRowCounts setObject:[NSNumber numberWithInt:rowCount] forKey:sectionTitle];
[sectionTitles addObject:sectionTitle];

答案 2 :(得分:0)

是的,继续尝试使用NSMutableDictionary。这是您需要的数据结构。您可以发布您的代码,看看为什么它没有返回您期望的值吗?

示例:

NSString *yourvalue = @"Hello!";
NSMutableDictionary *d;
[d setValue:yourvalue forKey:@"yourkey"];
NSString *retrievedvalue = [d valueForKey:@"yourkey"];
// you should get value here