2016-04-27 59 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