2015-09-28 44 views
-3

我有一個數組,它在JSON查詢中接收它,按照字母順序對數組進行排序。填充UITableView窗體數組從JSON中收集部分

我設法按字母順序對數組進行排序,但我無法將此數組拆分爲多個部分。

我發現一個NSDicctionary的例子,但我不知道如何填充它。提前致謝!

animals = @{@"B" : @[@"Bear", @"Black Swan", @"Buffalo"], 
      @"C" : @[@"Camel", @"Cockatoo"], 
      @"D" : @[@"Dog", @"Donkey"], 
      @"E" : @[@"Emu"], 
      @"G" : @[@"Giraffe", @"Greater Rhea"], 
      @"H" : @[@"Hippopotamus", @"Horse"], 
      @"K" : @[@"Koala"], 
      @"L" : @[@"Lion", @"Llama"], 
      @"M" : @[@"Manatus", @"Meerkat"], 
      @"P" : @[@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear"], 
      @"R" : @[@"Rhinoceros"], 
      @"S" : @[@"Seagull"], 
      @"T" : @[@"Tasmania Devil"], 
      @"W" : @[@"Whale", @"Whale Shark", @"Wombat"]}; 
+0

你想用這本詞典做什麼? – abhi1992

+0

對不起rmaddy,我想知道爲什麼「iphone」和「xcode」標籤與你認爲 – garatu

+0

這個問題關係不大,特別是關於tableview和nsdictionary的問題。你的問題並沒有解決iphone/xcode的問題。因此相關性很差! –

回答

2

如果這是你回來

NSArray* animals = @[@"Bear", @"Black Swan", @"Buffalo",@"Camel", @"Cockatoo",@"Dog", @"Donkey",@"Emu",@"Giraffe", @"Greater Rhea",@"Hippopotamus", @"Horse",@"Koala",@"Lion", @"Llama",@"Manatus", @"Meerkat",@"Panda", @"Peacock", @"Pig", @"Platypus", @"Polar Bear",@"Rhinoceros",@"Seagull",@"Tasmania Devil",@"Whale", @"Whale Shark", @"Wombat"]; 

你可以做這樣的事情來獲取字典

NSArray* alphabets = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"]; 
NSMutableDictionary* indexedAnimals = [NSMutableDictionary dictionary]; 
for (NSString* letter in alphabets) 
{ 
    NSArray* filteredAnimals = [animals filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSString* evaluatedObject, NSDictionary *bindings) 
    { 
     return [evaluatedObject hasPrefix:letter]; 
    }]]; 
    if ([filteredAnimals count]) 
    { 
     indexedAnimals[letter] = filteredAnimals; 
    } 
} 
NSArray* sectionLetters = [[indexedAnimals allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

然後配置表視圖陣列

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [sectionLetters count]; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    return sectionLetters[section]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return [indexedAnimals[sectionLetters[section]] count] 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CellId" forIndexPath:indexPath]; 

    NSString *animal = indexedAnimals[sectionLetters[indexPath.section]][indexPath.row]; 
    cell.textLabel.text = animal; 

    return cell; 
} 
+0

完美我的朋友!!!你是大!我很失落.. – garatu

+0

@garatu不客氣,很高興它幫助! –