按字母顺序将 NSMutableArray 数据动态排序到 NSDictionary 中

Dynamically sort NSMutableArray data into NSDictionary alphabetically

不幸的是,我的笔记本电脑目前没有互联网,所以我必须描述我的代码,我有一个 mutable 数组,其中包含按字母顺序排序的歌曲标题。我有一个 uitable 视图,目前正在显示这些,但是我想在 table 旁边有部分标题和字母表索引,所以我需要将这些歌曲放入 nsdictionary显示它,但是我无法在 nsdictionary.

准备数据的可能性有很多种。但是由于您的歌曲已经排序,您的视图控制器可能看起来像这样:

@interface TableViewController ()

@property (strong, nonatomic) NSArray *sectionTitles;
@property (strong, nonatomic) NSArray *songsInSections;

@end

@implementation TableViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    NSArray *songs = @[@"A song", @"Another song", @"Some other song", @"Yet another song"];

    // store all the needed section titles
    NSMutableArray *sectionTitles = [NSMutableArray array];
    // store the songs in sections (arrays in array)
    NSMutableArray *songsInSections = [NSMutableArray array];

    // prepare the data for the table view
    for (NSString *song in songs) {
        // get the song's section title (first letter localized and uppercased)
        NSString *sectionTitle = [[song substringToIndex:1] localizedUppercaseString];

        // check if a section for the song's section title has already been created and create one if needed
        if (sectionTitles.count == 0 || ![sectionTitle isEqualToString:sectionTitles[sectionTitles.count - 1]]) {
            // add the section title to the section titles array
            [sectionTitles addObject:sectionTitle];
            // create an (inner) array for the new section
            [songsInSections addObject:[NSMutableArray array]];
        }

        // add the song to the last (inner) array
        [songsInSections[songsInSections.count - 1] addObject:song];
    }

    // "store" the created data to use it as the table view's data source
    self.sectionTitles = sectionTitles;
    self.songsInSections = songsInSections;
}

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

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.songsInSections[section] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.textLabel.text = self.songsInSections[indexPath.section][indexPath.row];
    return cell;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.sectionTitles;
}

@end