Кто-нибудь знает, как сделать индекс таблицы первыми 4 символами моего основного атрибута имени данных?

Я работаю над приложением монет. Монеты представляются пользователю в виде таблицы, управляемой Core Data.

Все названия монет начинаются с "19" или "20". Когда я реализую индекс раздела в табличном представлении, я получаю только "1" и "2" в моем индексе. Нажатие "1" перемещает стол к монете "1900", а нажатие "2" приводит меня к монете "2000". Я знаю, почему это происходит от первой цифры в поле имени.

То, что я хотел бы, это "1910", "1920", "1930" и т. Д., Чтобы пользователь мог перейти к десятилетию.

Я добавил атрибут "titleForSection" в модель, ввел "1910", "1920" и т. Д. И решил, что в моем наборе запросов на выборку sectionNameKeyPath указан мой атрибут "titleForSection". Излишне говорить, что это не работает.

Кто-нибудь знает, как сделать индекс раздела первыми 4 цифрами атрибута имени?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return [[fetchedResultsController sections] count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (self.searchIsActive) {
        return [self.filteredListContent count];
    }

    NSInteger numberOfRows = 0;

    if ([[fetchedResultsController sections] count] > 0) {
        id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
        numberOfRows = [sectionInfo numberOfObjects];
    }

    return numberOfRows;

}



//for index
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {

    return [fetchedResultsController sectionIndexTitles];

}


- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {

    return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

- (NSFetchedResultsController *)fetchedResultsController {

    if (fetchedResultsController != nil) {
        return fetchedResultsController;

    }

    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Coins" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    //set batch size
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"sortOrder" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"titleForSection" cacheName:nil];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;

    [aFetchedResultsController release];
    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    return fetchedResultsController;
}

ОБНОВИТЬ:

Я изменил свой атрибут titleForSection со строки на число, а затем заполнил базу данных с 1900 года вплоть до 2010 года, к десятилетию. Теперь мой табличный индекс отображается только с "0", "1" и "2". Я просто не понимаю, почему я не могу разместить там номер!

2 ответа

Вы должны переопределить – sectionIndexTitlesForTableView: в UITableViewController попробуйте что-то вроде этого:

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObject:@"1920"];
    [array addObject:@"1930"];
    [array addObject:@"1940"];
    [array addObject:@"1950"];
    [array addObject:@"1960"];
    [array addObject:@"1970"];

    return array;
}

Второй способ вас может заинтересовать:

– tableView:sectionForSectionIndexTitle:atIndex:

Просто создайте новый метод для вашего класса монет:

-(NSString*)firstFourCharsOfTitle
{
    return [[self titleForSection] substringToIndex:4];
}

и чем использовать этот метод для "sectionNameKeyPath" в инициализации NSFetchedResultsController

NSFetchedResultsController *aFetchedResultsController = 
     [[NSFetchedResultsController alloc] 
           initWithFetchRequest:fetchRequest 
           managedObjectContext:managedObjectContext 
             sectionNameKeyPath:@"firstFourCharsOfTitle" 
                      cacheName:nil];
Другие вопросы по тегам