[__NSCFString objectForKey:]: сбой при поиске по текстовому полю - PullRequest
0 голосов
/ 11 февраля 2019

Эта ошибка возникает при поиске данных в табличном представлении.Я использую текстовое поле в качестве панели поиска.Вот мой код:

NSMutableArray *searchArray;
NSString *searchTextString;
BOOL isFilter;
@property NSMutableArray *TableDataArray;


- (void)viewDidLoad {
    [super viewDidLoad];
    [self.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self updateSearchArray];
    [self.tableView reloadData];
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [searchArray count];
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"SubNotificationCell";
    SubNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    NSDictionary *dict;
    if(isFilter) {
        dict = [[self->searchArray objectAtIndex:indexPath.row] objectForKey:@"Eqktx"];
    } else {
       dict = [self.EtNotifRepTableDataArray objectAtIndex:indexPath.row];
    }

    NSString* notifValue = [dict objectForKey:@"Qmnum"];
    NSString* equipNameValue = [dict objectForKey:@"Eqktx"];
    NSString *values = @":";
    cell.notifValueLabel.text = [NSString stringWithFormat: @"%@ %@", values, notifValue];
    cell.equipNameValueLabel.text = [NSString stringWithFormat: @"%@ %@", values, equipNameValue];
    return cell;
}

-(void)textFieldDidChange:(UITextField*)textField {
    searchTextString = textField.text;
    [self updateSearchArray];
}

-(void)updateSearchArray {
    if (searchTextString.length != 0) {
        isFilter=YES;
        searchArray = [NSMutableArray array];
        for ( NSDictionary* item in _EtNotifRepTableDataArray ) {
            if ([[[item objectForKey:@"Eqktx"] lowercaseString] rangeOfString:[searchTextString lowercaseString]].location != NSNotFound) {
                [searchArray addObject:item];
            }
        }
    } else {
        isFilter=NO;
        searchArray = _EtNotifRepTableDataArray;
    }

    [self.tableView reloadData];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

Мне нужно искать как число, так и строку.Но происходит сбой с приведенной ниже ошибкой:

*** Завершение работы приложения из-за необработанного исключения «NSInvalidArgumentException», причина: '- [__NSCFString objectForKey:]: нераспознанный селектор, отправленный экземпляру 0x280e083f0'

по моему viewdidload

@property NSMutableArray *EtNotifRepTableDataArray;

_EtNotifRepTableDataArray = [[NSMutableArray alloc]init];
    for (NSDictionary *dict in arr) {
        [dict description];
        NSString *Qmart = [dict objectForKey:@"Qmart"];
        NSString *Phase = [dict objectForKey:@"Phase"];
        if ([Qmart isEqualToString:_qmartValue] && [Phase isEqualToString:_phaseValue]){

            [self.EtNotifRepTableDataArray addObject:dict];
        }
    }

1 Ответ

0 голосов
/ 11 февраля 2019

Вы заменяете ваш метод cellForRowAtIndexPath этим.

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath { 
    static NSString *CellIdentifier = @"SubNotificationCell";
    SubNotificationCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    NSDictionary *dict;
    if(isFilter) {
        // HERE was the problem. 
        //dict = [[self->searchArray objectAtIndex:indexPath.row] objectForKey:@"Eqktx"];
        dict = [self.searchArray objectAtIndex:indexPath.row]
    } else {
       dict = [self.EtNotifRepTableDataArray objectAtIndex:indexPath.row];
    }

    NSString* notifValue = [dict objectForKey:@"Qmnum"];
    NSString* equipNameValue = [dict objectForKey:@"Eqktx"];
    NSString *values = @":";
    cell.notifValueLabel.text = [NSString stringWithFormat: @"%@ %@", values, notifValue];
    cell.equipNameValueLabel.text = [NSString stringWithFormat: @"%@ %@", values, equipNameValue];
    return cell;
}

Проблема в том, что вы выбираете объект непосредственно в части фильтра метода cellForRowAtIndexPath, который возвращает вам значение NSString, а затем снова ввы пытаетесь получить objectForKey из этой строки NSString, которая приводит к сбою, поскольку у NSString нет известного метода objectForKey

РЕДАКТИРОВАТЬ:

Это не связано с падением, но вы должны такжеобновите этот метод на основе фильтра.

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(isFilter) {
        return [searchArray count];
    } else {
        return [self.EtNotifRepTableDataArray count];
    }
}

Попробуйте поделиться своими результатами.

...