UITableView 从 NSArray 动态创建部分

UITableView Dynamically Create Sections from NSArray

我有以下数据结构,我不能改变(可能是这个问题最重要的部分):

<?xml version="1.0" encoding="us-ascii"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <array>
    <dict>
      <key>FirstName</key>
      <string>John</string>
      <key>LastName</key>
      <string>Adams</string>
    </dict>
    <dict>
      <key>FirstName</key>
      <string>Henry</string>
      <key>LastName</key>
      <string>Ford</string>
    </dict>
  </array>
</plist>

我可以成功地将其读入 NSArray 的 class 类型的 Person(我创建的),并在 UITableView 中显示此列表。

现在我想对这些数据做的是按部分显示它,按他们姓氏的第一个字母显示 SectionIndexList.

我如何转换此数据(不是数据源),或保持它完好无损并直接在我的 DataSource 中查询 UITableView,这样我就可以按第一个字母将其分割他们的姓?

提前致谢。

你应该这样做:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"name_of_plist" ofType:@"plist"];
NSArray *personsFileArray = [NSArray arrayWithContentsOfFile:filePath];
// At this point what you have inside personsFileArray are NSDictionaries as defined in your plist file. You have a NSArray<NSDictionary*>.
NSMutableDictionary *indexedPersons = [[NSMutableDictionary alloc] init];
// I am assuming you have a class called Person
for each (NSDictionary *d in personsFileArray) {
   Person *p = [[Person alloc] initWithDictionary:d];
   NSString *firstLetter = [p.lastName substringToIndex:1];
   NSMutableArray *persons = indexedPersons[firstLetter];
   if (!persons) {
      persons = [[NSMutableArray alloc] init];
   }
   [persons addObject:p];
   [indexedPersons setObject:persons forKey:firstLetter];
}
// After this, you have a dictionary indexed by the first letter, and as key an array of persons. 
// Now you need to implement UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *firstLetter = [self.indexedPersons allKeys][section];
    return self.indexedPersons[firstLetter].count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
    return [self.indexedPersons allKeys].count;
}

并为章节索引标题实现此方法;

- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;

如有疑惑,教程多多:

http://www.appcoda.com/ios-programming-index-list-uitableview/

希望对您有所帮助!!