Reputation: 3215
I have the following data structure, which I cannot change (probably the most important part of this question):
<?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>
I can successfully read this into an NSArray
of class type of Person
(which I created) and well as show this list in a UITableView
.
What I would like to do with this data now is show it in sections, by the first letter in their last name as well as show the SectionIndexList
.
How can I transform this data (not the data source), or leave it intact and query it directly in my DataSource
for UITableView
so I can section it off by the first letter in their last name?
Thanks in advance.
Upvotes: 0
Views: 374
Reputation: 559
You should do something like:
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;
}
And implement this methods for the section index titles;
- (nullable NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;
- (nullable NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView;
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;
If you have any doubts, there are plenty of tutorials:
http://www.appcoda.com/ios-programming-index-list-uitableview/
Hope it helps!!
Upvotes: 1