【发布时间】:2010-11-18 19:59:04
【问题描述】:
我有一个 plist,其中包含一个带有字典集合的数组。数组中的字典用于创建一个相当复杂的表格视图,每个单元格中有 2 个图像和 2 行文本。我想根据与“MainText”键对应的值的第一个字母在表格视图中创建部分。
这里是 plist 格式。在此示例中,应该有 2 个部分,一个用于“MainText”字符串以“A”开头的字典,一个用于“MainText”字符串以“B”开头的 2 个字典。
<dict>
<key>Rows</key>
<array>
<dict>
<key>MainText</key>
<string>A sometext</string>
<key>SecondaryText</key>
<string>somemoretext</string>
<key>PrimaryIcon</key>
<string>firsticon.png</string>
<key>SecondaryIcon</key>
<string>secondicon.png</string>
</dict>
<dict>
<key>MainText</key>
<string>B sometext</string>
<key>SecondaryText</key>
<string>somemoretext</string>
<key>PrimaryIcon</key>
<string>firsticon.png</string>
<key>SecondaryIcon</key>
<string>secondicon.png</string>
</dict>
<dict>
<key>MainText</key>
<string>B moreTextStartingWith"B"</string>
<key>SecondaryText</key>
<string>somemoretext</string>
<key>PrimaryIcon</key>
<string>firsticon.png</string>
<key>SecondaryIcon</key>
<string>secondicon.png</string>
</dict>
</array>
我已经编写了代码,用于从“MainText”键处的字符串中提取第一个字母,对它们进行排序并创建节标题。我还有用于在每个部分中设置正确行数的代码。这是我在 viewDidLoad 方法中纠结的一些代码。
//Create an array sorted by the strings in "MainText" of the AppDelegate.data
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"MainText" ascending:YES] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [[AppDelegate.data objectForKey:@"Rows"] sortedArrayUsingDescriptors:sortDescriptors];
//Now set tableDataSource equal to sortedArray
self.tableDataSource = sortedArray;
//Create a set of the first letters used by the strings in MainText
NSMutableSet *firstCharacters = [NSMutableSet setWithCapacity:0];
for( NSString *string in [tableDataSource valueForKey:@"MainText"] )
[firstCharacters addObject:[string substringToIndex:1]];
//Create a sorted array of first letters used by strings in MainText
self.arrayOfInitialLetters = [[firstCharacters allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
//Create an array of the MainText of each item in tableDataSource
NSMutableArray * mainTextArray = [tableDataSource valueForKey:@"MainText"];
我应该如何在 cellForRowAtIndexPath 方法中获取正确的行?目前,每个部分只显示从第一个开始的相同单元格。我需要以某种方式在我的数据源中定义有不同的部分。感谢您的帮助,这是一场真正的斗争!
【问题讨论】:
-
在您的 plist 中,我认为它应该以第二个结束 读取,并且 应该在末尾?...
-
是的。它一定是在副本中丢失了。我在上面更正了。
标签: iphone arrays uitableview dictionary