简体   繁体   中英

Searching arrays of objects with NSPredicate

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {

    [displayItems removeAllObjects];  //clear array to ensure no repeat info
    if ([searchText length] == 0) {
        displayItems = (NSMutableArray *)allItems;
    }
    else {
        //search by item category
        NSPredicate *catPredicate = [NSPredicate predicateWithFormat:@"category   
            CONTAINS[cd] %@",searchText];
        [searchable filterUsingPredicate:catPredicate];
        //further search by item name
        NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd]
            %@",searchText];
        [searchable filterUsingPredicate:namePredicate];

        displayItems = searchable;
        searchable = (NSMutableArray *)allItems;
    }
    [self.searchResults reloadData];
}

This method is part of a simple searchable table view I am trying to create for a larger project. My code compiles and runs, and when i type something into the search bar the search function appears to work, but then the program crashes as soon as a second letter is typed. If I type two letters in a row, it throws 'NSInvalidArgumentException', reason: '-[_ NSArrayI filterUsingPredicate:]: unrecognized selector sent to instance 0x6d6c040' , but if I type one letter and then hit enter or backspace, it throws this guy 'NSInvalidArgumentException', reason: '-[ _NSArrayI removeAllObjects]: unrecognized selector sent to instance 0x6a7f300' when I type a second letter.

I am pretty new to objective-c, and this has me perplexed. Any help I could get would be greatly appreciated.... :-/ Still having issues since update.

"One does not simply cast NSArray into NSMutableArray and then call NSMutableArray methods on it" - Boromir

Create a mutable copy instead, like this:

searchable = [allItems mutableCopy];

NOTE: Make sure to release searchable when you are finished with it.

You have to use NSMutableArray to call the methods.

NSArray has a method "filteredArrayusingPredicate".

The simple solution is use NSMutableArray.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM