I have this code to search in a String particular words like Canada Poland México
Example:
NSString *valueOfUser = #"I want Poland"
NSPredicate *pred =[NSPredicate predicateWithFormat: #"SELF contains[c] %#", valueOfUser];
NSArray *arr = #[
#"Canada",
#"Poland",
#"México"
];
NSArray *filtered = [arr filteredArrayUsingPredicate: pred];
// But this array always contain 0 elements
Where is my error?
I want to find a solution like:
NSString *valueOfUser = #"I want Poland"
filtered[0] -> "Poland"
NSString *valueOfUser = #"I choose Poland and México"
filtered[0] -> "Poland"
filtered[1] -> "México"
Your query should be opposite:
valueOfUser CONTAINS[c] SELF, try this:
Objective C:
NSString *valueOfUser = #"I want Poland";
NSPredicate *pred =[NSPredicate predicateWithFormat: #"%# contains[c] SELF", valueOfUser];
NSArray *arr = #[
#"Canada",
#"Poland",
#"México"
];
NSArray *filtered = [arr filteredArrayUsingPredicate: pred];
Swift:
let dataSource = ["Canada","Poland","México"] as NSArray
let searchString = "I choose Poland and México"
let predicate = NSPredicate(format: "%# contains[c] SELF", searchString)
let dataArray = dataSource.filter { predicate.evaluate(with: $0) }
Some people find this more readable
NSString *valueOfUser = #"I want Poland";
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSString *evaluatedObject, NSDictionary *bindings) {
return [valueOfUser containsString:evaluatedObject];
}];
NSArray *arr = #[
#"Canada",
#"Poland",
#"México"
];
NSArray *filtered = [arr filteredArrayUsingPredicate:predicate];
Related
I have array of custom objects, _momsArray. shown here is single object of such array:
Custom *yourMom {
name = #"Sally M. Brown";
age = 54;
weight = 43.2;
}
I run my predicate inside searchBar delegate:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([searchText length]<=0) {
_tableDataArr = [[NSMutableArray alloc] initWithArray:_momsArray];
} else{
// filtered _tableDataArr
NSString *filter = #"name BEGINSWITH[cd] %#";
NSPredicate* predicate = [NSPredicate predicateWithFormat:filter, searchText];
NSArray *filteredArr = [_momsArray filteredArrayUsingPredicate:predicate];
_tableDataArr = [[NSMutableArray alloc] initWithArray:filteredArr];
}
[_momTable reloadData];
}
This doesn't give expected result. For example, when I type S, sally doesn't appear at all. What is wrong with my code?
EDIT: The string in the custom objects contains punctuations and therefore it is not the same as other answers.
To filter an array with custom objects you can use this code.
NSString *str = #"text";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.name contains[c] %#", str];
NSArray *arrFiltered = [self.arrDataObject filteredArrayUsingPredicate:predicate];
Hope, it helps.
Your string is not properly generated so use below code :
NSPredicate *predicate = [ NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", text];
arrFilterData = [NSArray arrayWithArray:[arrDataList filteredArrayUsingPredicate:predicate]];
OUTPUT
Before search
After search
And with code
NSPredicate *predicate = [ NSPredicate predicateWithFormat:#"SELF CONTAINS[c] %#", text];
arrFilterData = [NSArray arrayWithArray:[arrDataList filteredArrayUsingPredicate:predicate]];
OutPut:
Edit
Output :
Use this code :
NSPredicate *pred = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", searchText];
NSMutableArray *filteredArr = [[_momsArray filteredArrayUsingPredicate:pred]mutableCopy];
I'm trying to use the input on an NSTextField along with NSPredicate to populate a NSMutableArray of like objects.
In my app I have the following simple NSMutableArray
{
firstName = Danton;
phoneNumbers = 5555555555;
}
Now, I am using the following code to try and filter the results as the user types (if "Dan" is in the textField, the filtered array should include the above object)
NSMutableArray *filteredArray = [[NSMutableArray alloc] init];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"firstName CONTAINS[cd] %#", self.searchField.text];
filteredArray = [[filteredArray filteredArrayUsingPredicate:sPredicate] mutableCopy];
NSLog(#"Filtered values: %#", filteredArray);
However, I am getting an empty return on filteredArray. Can someone tell me what is wrong with my code?
NSArray *array = #[
#{
#"firstName" : #"Danton", #"phoneNumbers" : #"5555555555"
}
];
NSArray *result = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"%K contains[c] %#", #"firstName", #"Dan"]];
while implementing search functionality I need to filter array of dictionaries. I am using auto complete textfield method for search bar and am storing it into string. I can able to parse the array,But facing with below json
[{"CertProfID":"4","Name":"Dodge","Location":"loc4","City":"city4","State":"state4","Zip":"zip5","Website":"http:\/\/cnn.com","Phone":"phone4","Email":"email4"},
{"CertProfID":"5","Name":"cat","Location":"loc5","City":"city5","State":"State5","Zip":"zip5","Website":"web5","Phone":"phone5","Email":"email5"}]
Here I need to filter the dictionaries to make it finish
I tried with below code but its returning array with null values :(
NSString *substring = [NSString stringWithString:textField.text];
NSLog(#"substring %#",substring);
NSMutableArray *arr2Filt= [arraylist valueForKey:#"Name"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",substring];
filteredarr = [NSMutableArray arrayWithArray:[arr2Filt filteredArrayUsingPredicate:predicate]];
This code will solve your problem it will return an array of dictionaries
NSString *substring = [NSString stringWithString:textField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Name contains[c] %#",searchString];
NSArray *filteredArry=[[arrayOfDict filteredArrayUsingPredicate:predicate] copy];
arrayOfDict is your original array of dictionaries
Swift 4.2 Version:::
let namePredicate = NSPredicate(format: "Name contains[c] %#",searchString)
let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) }
print("names = \(filteredArray)")
Hope it will help you
You could use blocks instead. They are much less hand-wavy about match conditions.
NSString *substring = [NSString stringWithString:textField.text];
NSLog(#"substring %#",substring);
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject[#"Name"] containsString:substring];
}];
filteredarr = [NSMutableArray arrayWithArray:[arraylist filteredArrayUsingPredicate:predicate]];
Here one observation is that filteredArrayUsingPredicate is a method of NSArray and you are using NSMutableArray instead.
Change NSMutableArray with temporary NSArray object for predicate.
For example:
NSString *substring = [NSString stringWithString:textField.text];
NSArray *tempArray = [arraylist valueForKey:#"Name"];
// If [arraylist valueForKey:#"Name"]; line returns NSMutableArray than use below line
// NSArray *tempArray = [NSArray arrayWithArray:[arraylist valueForKey:#"Name"]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",substring];
filteredarr = [[tempArray filteredArrayUsingPredicate:predicate] mutableCopy];
Hi I know there is many any answer,
In my case I have stored values As JSON MODEL object, This is code for, using JSON MODEL
NSString *searchString = searchBar.text;
NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSDictionary *temp=[evaluatedObject toDictionary];
return [temp[#"user"][#"firstName"] localizedCaseInsensitiveContainsString:searchString];
}];
filteredContentList = [NSMutableArray arrayWithArray:[searchListValue filteredArrayUsingPredicate:predicate]];
[tableViews reloadData];
searchListValue is a NSMutableArray which contains Array of json model objects.If anyone need help regarding this, just ping me
Swift version above 2.2
var customerNameDict = ["firstName":"karthi","LastName":"alagu","MiddleName":"prabhu"];
var clientNameDict = ["firstName":"Selva","LastName":"kumar","MiddleName":"m"];
var employeeNameDict = ["firstName":"karthi","LastName":"prabhu","MiddleName":"kp"];
var attributeValue = "ka";
var arrNames:Array = [customerNameDict,clientNameDict,employeeNameDict];
//var namePredicate =
// NSPredicate(format: "firstName like %#",attributeValue);
//uncomment above line to search particular word
let namePredicate =
NSPredicate(format: "firstName contains[c] %#",attributeValue);
let filteredArray = arrNames.filter { namePredicate.evaluateWithObject($0) };
print("names = ,\(filteredArray)");
More about this refer here
I want to query an NSDictionary of contacts using NSPredicate. I am able to search the contacts using the "firstName" and "lastName" separately, but I also need to search the contacts whose complete name is entered.
For example: If I want to search a contact with name "John Doe", and I search by entering search key "John" or "Doe", I am able to get the name, but I also want it to be searchable when I enter search key "John Doe". Currently I am using :
NSPredicate *p1 = [NSPredicate predicateWithFormat:#"lastNames BEGINSWITH[cd] %#", searchText];
NSArray *p1FilteredArray = [allContacts filteredArrayUsingPredicate:p1];
NSPredicate *p2 = [NSPredicate predicateWithFormat:#"firstNames BEGINSWITH[cd] %#", searchText];
NSArray *p2FilteredArray = [allContacts filteredArrayUsingPredicate:p2];
searchedArray = [[p1FilteredArray arrayByAddingObjectsFromArray:p2FilteredArray] mutableCopy];
You can use single predicate with or operator:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"firstNames beginswith[cd] %# or lastNames beginswith[cd] %#", searchTerm, searchTerm];
NSArray *results = [allContacts filteredArrayUsingPredicate:predicate];
I would do something like e.g. this:
NSArray *_allContacts = // ...;
NSString *_searchText = // ...;
NSArray *_result = [_allContacts filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary * evaluatedObject, NSDictionary *bindings) {
return ([[[evaluatedObject valueForKey:#"lastNames"] lowercaseString] hasPrefix:[_searchText lowercaseString]] || [[[evaluatedObject valueForKey:#"firstNames"] lowercaseString] hasPrefix:[_searchText lowercaseString]]);
}]];
I have an NSArray with objects that have a name property.
I would like filter the array by name
NSString *alphabet = [agencyIndex objectAtIndex:indexPath.section];
//---get all states beginning with the letter---
NSPredicate *predicate =
[NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", alphabet];
NSMutableArray *listSimpl = [[NSMutableArray alloc] init];
for (int i=0; i<[[Database sharedDatabase].agents count]; i++) {
Town *_town = [[Database sharedDatabase].agents objectAtIndex:i];
[listSimpl addObject:_town];
}
NSArray *states = [listSimpl filteredArrayUsingPredicate:predicate];
But I get an error - "Can't do a substring operation with something that isn't a string (lhs = <1, Arrow> rhs = A)"
How can I do this? I would like to filter the array for the first letter in name being 'A'.
Try with following code
NSPredicate *pred = [NSPredicate predicateWithFormat:#"SELF like %#", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];
EDITED :
NSPredicate pattern should be:
NSPredicate *pred =[NSPredicate predicateWithFormat:#"name beginswith[c] %#", alphabet];
Here is one of the basic use of NSPredicate for filtering array .
NSMutableArray *array =
[NSMutableArray arrayWithObjects:#"Nick", #"Ben", #"Adam", #"Melissa", #"arbind", nil];
NSPredicate *sPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] 'b'"];
NSArray *beginWithB = [array filteredArrayUsingPredicate:sPredicate];
NSLog(#"beginwithB = %#",beginWithB);
NSArray offers another selector for sorting arrays:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(Person *first, Person *second) {
return [first.name compare:second.name];
}];
If you want to filter array take a look on this code:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == %#", #"qwe"];
NSArray *result = [self.categoryItems filteredArrayUsingPredicate:predicate];
But if you want to sort array take a look on the following functions:
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context;
- (NSArray *)sortedArrayUsingFunction:(NSInteger (*)(id, id, void *))comparator context:(void *)context hint:(NSData *)hint;
- (NSArray *)sortedArrayUsingSelector:(SEL)comparator;
visit https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Collections/Articles/Arrays.html
use this
[listArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
Checkout this library
https://github.com/BadChoice/Collection
It comes with lots of easy array functions to never write a loop again
So you can just do
NSArray* result = [thArray filter:^BOOL(NSString *text) {
return [[name substr:0] isEqualToString:#"A"];
}] sort];
This gets only the texts that start with A sorted alphabetically
If you are doing it with objects:
NSArray* result = [thArray filter:^BOOL(AnObject *object) {
return [[object.name substr:0] isEqualToString:#"A"];
}] sort:#"name"];