На самом деле у меня очень простая проблема (это точно). Я просто не могу найти основную причину.
Проблема в том, что после вызова метода numberOfSectionsInTableView для получения количества разделов (в моем случае 24) вызывается метод numberOfRowsInSection, но с последним разделом (23).
При прокрутке это вызывает недопустимый индекс.
Итак, что происходит?
Я получаю данные последнего раздела (23) и даже количество строк в последнем разделе (23), а затем разделы перемещаются вперед, как 0,1,2,3 и т. Д. *
Пример:
У меня есть раздел с заголовком раздела "#" для специальных символов. В моем случае последний раздел - это «X» для всех значений, начинающихся с «X».
Когда я вызываю мое приложение, заголовок раздела был правильно установлен на "#", но данные показывают все значения "X".
На данный момент у меня есть 31 "X" значения. Когда я теперь прокручиваю до последней из 31 строки, приложение вылетает из-за ошибки отсутствия индекса.
Я думаю, что все будет работать правильно, если разделы не начнутся с последнего, а затем продолжатся с первыми (23,0,1,2,3,4 и т. Д.).
Я просто не могу найти место, где или почему раздел имеет значение 23 на первом месте.
--- РЕДАКТИРОВАТЬ 2 НАЧИНАЕТ:
инициализация массива:
alphabetArray = [[NSMutableArray alloc] init];
Сначала я заполняю словарь следующим образом (для всех букв, включая специальные символы):
charDict = [[NSMutableDictionary alloc] init];
if ([charSpecialArray count] > 0) {
[charDict setObject:charSpecialArray forKey:@"Special"];
[alphabetArray addObject:@"Special"];
}
if ([charAArray count] > 0) {
[charDict setObject:charAArray forKey:@"A"];
[alphabetArray addObject:@"A"];
}
--- РЕДАКТИРОВАТЬ 2 КОНЦА
Итак, я просто заполняю первый словарный объект всеми значениями "#" (продолжая со всеми другими значениями)
Затем я вызываю метод numberOfSectionsInTableView:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [charDict count];
}
здесь идет число OfFowsInSection:
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *key = [alphabetArray objectAtIndex:section];
NSArray *array = [charDict objectForKey:key];
return [array count];
}
}
и ячейка ForRowAtIndexPath:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil)
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease];
if ([charSpecialArray count] > 0) {
Char *charSpecial = (Char *)[[charSpecialArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.numberOfLines = 1;
cell.detailTextLabel.numberOfLines = 2;
[cell.detailTextLabel setFont:[UIFont boldSystemFontOfSize: 12]];
cell.textLabel.text = charSpecial.ta;
cell.detailTextLabel.text = charSpecial.descriptionEN;
}
if ([charAArray count] > 0) {
Char *charA = (Char *)[[charAArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.numberOfLines = 1;
cell.detailTextLabel.numberOfLines = 2;
[cell.detailTextLabel setFont:[UIFont boldSystemFontOfSize: 12]];
cell.textLabel.text = charA.ta;
cell.detailTextLabel.text = charA.descriptionEN;
}
снова для всех персонажей ...
Есть предложения, как это исправить?
добавил
код инициализации .h:
#import <UIKit/UIKit.h>
@interface Char : NSObject {
NSString *ta;
NSString *report;
NSString *descriptionDE;
NSString *descriptionEN;
}
@property (nonatomic, retain) NSString *ta;
@property (nonatomic, retain) NSString *report;
@property (nonatomic, retain) NSString *descriptionDE;
@property (nonatomic, retain) NSString *descriptionEN;
-(id)initWithTa:(NSString *)t report:(NSString *)re descriptionDE:(NSString *)dde descriptionEN:(NSString *)den;
@end
код инициализации .m:
#import "SCode.h"
@implementation Char
@synthesize ta, report, descriptionDE, descriptionEN;
-(id)initWithTa:(NSString *)t report:(NSString *)re descriptionDE:(NSString *)dde descriptionEN:(NSString *)den {
self.ta = t;
self.report = re;
self.descriptionDE = dde;
self.descriptionEN = den;
return self;
}
- (void)dealloc {
[ta release];
[report release];
[descriptionDE release];
[descriptionEN release];
[super dealloc];
}
@end