开发者

iOS Cotains-based Predicate search only returns when exact match found

I'm adding a search bar to a table view component of my iOS application that allows searching through an NSArray comprised of Dictionaries. The search bar does not work all the time, though - it successfully prints out a result if there is an exact match for my data, but not a partial match. For instance, it will print out "Turn off a light" as a result if that exact phrase is entered, but not if just "Turn" is entered. On a debugging array made only of strings, however, the search functionality worked exactly as expected.

My predicate code is here:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{

NSPredicate *re开发者_Python百科sultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];

self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];

}

The test block that actually worked was written like this:

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] %@", searchText];

NSArray *array = [NSArray arrayWithObjects:@"Miguel", @"Ben", @"Adam", @"Melissa", nil];

NSArray *moreStuff = [array filteredArrayUsingPredicate:resultPredicate];

NSLog(@"%@", moreStuff);

self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];

}

In the above block of code, the NSArray "moreStuff" printed out and updated correctly, however in the first block the NSArray "searchResults" only returns a result when an exact match is entered. I'm at a complete loss here, so any help/recommendations will be super appreciated.


Because you are searching for a string in an object, I think you just need to dig a bit deeper in your predicate. A string within the object is only a partial match of that object. When you use SELF in the predicate, you're specifying to search within the object itself, which in your case is an NSDictionary. String fields in the NSDictionary are essentially objects within an object. So if you are looking for a field called 'Name' in your Dictionary, instead of having the predicate look in SELF, it should look in SELF.Name. You could try the following code to search the Name field of your NSDictionary.

- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{

NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF.Name CONTAINS[cd] %@", searchText];

self.searchResults = [allSearchableItems filteredArrayUsingPredicate:resultPredicate];

}

If you still need to check other fields contained within the object, you can create a compound predicate. Details on Predicates can be found in Apple's Predicate Programming Guide.

I hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜