Array of filter from dictionary and string

I have one array that contains an array of dictionary and strings and I want a filter with a dictionary value, but when I do the filtering, I get the result only when I type the first letter in the text box, I wrote this code to search for nspredicate also I added a screenshot for NSarry containing the values ​​that I use for filtering.

Here is the code to search for an array:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string; // return NO to not change text { NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSLog(@"%@",searchStr); NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF contains[c] %@ ",searchStr]; NSArray *filteredArr = [arrmainData filteredArrayUsingPredicate:predicate]; detailListArray=[[NSMutableArray alloc]initWithArray:filteredArr]; [tblGlosary reloadData]; return true; } 

Here is the screen for the array

enter image description here

+5
source share
1 answer

You have an array of mixed types ( NSString and NSDictionary ), which is usually a very bad idea (and will not be possible in Swift).

If for some reason you cannot control this and really need to filter through it, you need to check the validity of the comparison depending on the type:

 NSIndexSet *matches = [arrmainData indexesOfObjectsPassingTest:BOOL^(id obj, NSUInteger idx, BOOL *stop) { NSString *stringToCompare = nil; if ([obj isKindOfClass:[NSString class]]) { stringToCompare = (NSString *)obj; } else { NSDictionary *dict = (NSDictionary *)obj; stringToCompare = dict["Name"]; } return [stringToCompare rangeOfString:searchString].location != NSNotFound; }]; NSArray *filteredArray = [arrmainData objectsAtIndexes:matches]; 

But then again, if you can really rethink mixing types in a single array, this is likely to lead to problems in the future.

0
source

All Articles