I would like to use searchbar in my tableView. I have an NSArray with Person (NSObject). In cellForRow I'm using this code :
Person *person = [[self.sectionedPersonName objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
cell.textLabel.text = person.fullName;
and for searchBar this code :
- (void)searchForText:(NSString *)searchText {
if (searchText.length > 0) {
searchBar = YES;
} else {
searchBar = NO;
}
NSLog(@"%@", self.sectionedPersonName);
NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText];
self.searchResults = [self.sectionedPersonName filteredArrayUsingPredicate:predicate];
}
self.sectionedPersonName
contains this :
(
(
"<Person: 0x7fc0f6012650>"
),
(
),
(
),
(
"<Person: 0x7fc0f600f8a0>",
"<Person: 0x7fc0f60132e0>"
),
(
),
(
),
(
),
(
"<Person: 0x7fc0f6012d80>"
),
(
),
(
"<Person: 0x7fc0f6012b30>"
),
(
"<Person: 0x7fc0f6010100>"
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
),
(
)
)
So my question is how to make an NSPredicate on this ? I have tried this, but doesn't work:
NSPredicate *predicate; = [NSPredicate predicateWithFormat:@"SELF.fullName beginswith[c] %@", searchText];
Error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do a substring operation with something that isn't a string (lhs = (
"Anna Haro"
) rhs = )'
You don't have an array of people, you have an array of arrays of people. So, you can't simply filter the array because all your comparisons are actually trying to compare arrays of strings with strings. This is the reason for the 'strange' results and crashes you see.
Your best option is to create your own loop to iterate over the outer array and then run your predicate on each inner array. Add the resulting filtered arrays to a new mutable array which holds the overall result.