2016-04-27 57 views
0
缔造出款款

我有以下数据结构,这是我无法改变(可能是这个问题的最重要的部分):的UITableView动态地从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>

我可以成功读取到这个类类型的NSArrayPerson(我创建的)以及在UITableView中显示此列表。

我现在想处理这些数据的方法是,按照姓氏的第一个字母以及显示SectionIndexList的部分显示。

我该如何转换这些数据(不是数据源),还是保持原样并直接在我的DataSource中查询UITableView,以便我可以用姓氏的第一个字母来区分它?

在此先感谢。

回答

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/

希望它可以帮助!

+0

谢谢!这很好!我无法描绘出逻辑。 – RoLYroLLs