我有以下数据结构,我无法改变(可能是这个问题最重要的部分):
<?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
类Person
(我创建的),并在UITableView
中显示此列表。
我现在要对这些数据做些什么,用章节中的第一个字母显示部分,并显示SectionIndexList
。
如何转换此数据(不是数据源),或将其保留原样并直接在DataSource
UITableView
中查询,以便我可以通过最后一个字母将其删除命名
提前致谢。
答案 0 :(得分:1)
您应该执行以下操作:
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/
希望它有所帮助!!