Итак, у меня есть UItableView, который автоматически заполняет ячейки на основе ввода пользователем. У меня есть главный массив имен Colors, называемый arrColors, и массив temp, называемый arrAutoCorrect, который заполняется, когда пользователь набирает.NSMutableArray выходит за пределы только при заполнении другим массивом
Оба массива - это NSMutableArrays.
Если пользователь очищает весь текст, массив temp должен быть полностью загружен из всех цветов. В цветовой гамме имеется 21 цвет (строки).
Я получаю индекс за пределы 17 (0 - 16).
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 17 beyond bounds [0 .. 16]'
Это сводит меня с ума.
Откуда это 17? Опять же, ошибка представляет только ее, когда пользователь очистил все содержимое текстового поля.
У меня есть NSLogged только обо всем, что я могу, и я не могу найти то, что называется этим 17 в диапазоне.
Мой код
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring :(NSMutableArray*) passedArray {
[self.arrAutoComplete removeAllObjects];
if ([substring length] == 0) {
//add all items
int count = 0;
for (NSString* c in passedArray) {
NSLog(@"Count: %i", count);
[self.arrAutoComplete addObject:c];
count++;
}
} else {
//Narrow down
for(NSString *curString in passedArray) {
NSRange substringRange = [curString rangeOfString:substring options:NSCaseInsensitiveSearch];
NSLog(@"my range is %@", NSStringFromRange(substringRange));
if (substringRange.location == 0) {
[self.arrAutoComplete addObject:curString];
}
}
}
[self.autocompleteTableView reloadData];
}
#pragma mark - TABLE VIEW DELEGATES
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
//NSLog(@"Number of sections to call for autocomplete table is: 1");
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// NSLog(@"Number of rows in section for autocomplete is: %lu", (long)[self.arrAutoComplete count]);
return [self.arrAutoComplete count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = nil;
//NSLog(@"Default cell delegate called");
NSUInteger section = [indexPath section];
// NSLog(@"Section: %lu", (unsigned long)section);
NSUInteger row = [indexPath row];
NSLog(@"Row : %lu", (unsigned long)row);
//NSLog(@"Cell for autocomplete called");
static NSString *AutoCompleteRowIdentifier = @"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
//NSLog(@"Cell for autocomplete was nil, createing new");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier];
}
//NSLog(@"Indes path row: %lu", indexPath.row);
cell.textLabel.text = [self.arrColors objectAtIndex:row];
//NSLog(@"Cell for autocomplete text should be: %@",[self.arrColors objectAtIndex:indexPath.row]);
return cell;
}
Мой журнал Краш
2015-02-04 17:47:46.512 App[4033:1312614] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 17 beyond bounds [0 .. 16]'
*** First throw call stack:
(
0 CoreFoundation 0x00000001037c9f35 __exceptionPreprocess + 165
1 libobjc.A.dylib 0x000000010310bbb7 objc_exception_throw + 45
2 CoreFoundation 0x00000001036c201e -[__NSArrayI objectAtIndex:] + 190
3 UIKit 0x0000000104193856 -[UITableViewDataSource tableView:heightForRowAtIndexPath:] + 109
4 UIKit 0x0000000103ec726b __66-[UISectionRowData refreshWithSection:tableView:tableViewRowData:]_block_invoke + 302
5 UIKit 0x0000000103ec68fe -[UISectionRowData refreshWithSection:tableView:tableViewRowData:] + 4125
6 UIKit 0x0000000103eca098 -[UITableViewRowData numberOfRows] + 97
7 UIKit 0x0000000103d328fc -[UITableView noteNumberOfRowsChanged] + 133
8 UIKit 0x0000000103d3203d -[UITableView reloadData] + 1316
Дополнительная информация: Если я закомментировать добавление всех цветов searchAutocompleteEntriesWithSubstring
где длина подстроки 0, то приложение не падает.
NSLog STATMENTS
2015-02-04 17:54:19.155 Tops[4065:1359488] Number of sections to call for autocomplete table is: 1
2015-02-04 17:54:19.155 Tops[4065:1359488] Number of rows in section for autocomplete is: 3
2015-02-04 17:54:19.156 Tops[4065:1359488] Default cell delegate called
2015-02-04 17:54:19.156 Tops[4065:1359488] Section: 0
2015-02-04 17:54:19.156 Tops[4065:1359488] Row : 0
2015-02-04 17:54:19.157 Tops[4065:1359488] Default cell delegate called
2015-02-04 17:54:19.157 Tops[4065:1359488] Section: 0
2015-02-04 17:54:19.157 Tops[4065:1359488] Row : 1
2015-02-04 17:54:19.158 Tops[4065:1359488] Default cell delegate called
2015-02-04 17:54:19.158 Tops[4065:1359488] Section: 0
2015-02-04 17:54:19.158 Tops[4065:1359488] Row : 2
2015-02-04 17:54:19.612 Tops[4065:1359488] Substring:
2015-02-04 17:54:19.612 Tops[4065:1359488] Count: 0
2015-02-04 17:54:19.612 Tops[4065:1359488] Count: 1
//Removed for brevity
2015-02-04 17:54:19.617 Tops[4065:1359488] Count: 19
2015-02-04 17:54:19.617 Tops[4065:1359488] Count: 20
2015-02-04 17:54:19.617 Tops[4065:1359488] Number of sections to call for autocomplete table is: 1
2015-02-04 17:54:19.618 Tops[4065:1359488] Number of rows in section for autocomplete is: 21
2015-02-04 17:54:19.622 Tops[4065:1359488] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 17 beyond bounds [0 .. 16]'
UPDATE ПОСТАНОВИЛИ
Я отсутствовал метод:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 60.0f;//some random number
}
Обязательно прочитайте документацию, детишки.
Можете ли вы опубликовать выходные данные из 'NSLog's? Исключение указывает, что в массиве 17 объектов, и вы пытаетесь получить доступ к 18-му (индекс 17, так как массивы начинаются с 0). На какой линии происходит сбой? – NobodyNada
В методе passArray имеется 21 объект для метода searchAutocompleteEntriesWithSubstring. Прошедшим в массиве является arrColors –
В какой строке он падает? – NobodyNada