I have an NSString which contains the folderName and i have an array which looks like this,
DATA (
{
FolderName = Posteingang;
ID = 13000;
},
{
FolderName = Freigaben;
ID = 13001;
},
{
FolderName = "My Drive";
ID = 13002;
},
{
FolderName = gsb;
ID = 13164;
},
{
FolderName = "my folder";
ID = 13183;
}
I would like to compare the array data with the NSString so i can remove the values from the string that do not match.
for (NSString *FileName in ParsedData)
{
NSRange FileNameRange = [FileName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (FileNameRange.location == NSNotFound) {
[SearchData removeObject:[SearchData valueForKey:#"FolderName"]];
}
}
I have this Fast Enumeration method and i have the Array SearchData. The enumeration method looks for the data in the array and if that data is not found then it should remove it from the array.The SearchData array is to be displayed in a tableview.
I have been trying the above method but it doesn't work.
NSString *searchText = #"Posteingang";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FolderName = %#",searchText];
NSMutableArray *predarr = [NSMutableArray arrayWithArray:[yourDATAArray filteredArrayUsingPredicate:predicate]];
if([predarr count]!=0)
{
NSLog(#"%#",predarr);
}
Use this :
NSString *matchString = #"Posteingang";
for (int i = 0; i > [dataArray count]; i++) // Here dataArray is your array
{
NSMutableDictionary *allDict = [dataArray objectAtIndex:i];
if ([[allDict objectForKey:#"FolderName"] isEqualToString:matchString]) {
[dataArray removeObjectAtIndex:i];
}
}
hope it helps you.
NSString *stringToBeMatched = #"Freigaben";
for (NSDictionary *itemDic in array)
{
if ([[itemDic objectForKey:#"FolderName"] isEqualToString:stringToBeMatched])
{
[dataArray removeObject:itemDic];
}
}
After a little help from all the answers above i figured out the solution on my own
for (NSDictionary *dict in [SearchData copy]){
NSString *folderName = [dict objectForKey:#"FolderName"];
NSRange range= [folderName rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(range.location == NSNotFound){
[SearchData removeObject:dict];
}
}
Try
NSArray *folders = #[#{#"FolderName":#"Posteingang",#"ID":#13000},
#{#"FolderName":#"Freigaben",#"ID":#13001},
#{#"FolderName":#"My Drive",#"ID":#13002},
#{#"FolderName":#"gsb",#"ID":#13164},
#{#"FolderName":#"my folder",#"ID":#13183}];
NSString *searchText = #"gsB";
//Choose a predicate that you want
//Case insensitive and diacritic search
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FolderName LIKE [cd] %#",searchText];
//Case sensitive search
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FolderName = %#",searchText];
//Any Matches
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FolderName CONTAINS [cd] %#",searchText];
NSArray *filteredArray = [folders filteredArrayUsingPredicate:predicate];
EDIT : Filtering using fast enumeration
for (NSDictionary *dict in [SearchData copy]){
NSString *folderName = dict[#"FolderName"];
if([searchText localizedCaseInsensitiveCompare:folderName]){
[SearchData removeObject:dict];
}
}
Related
Below is my model class
{"ID":1,"Name":"Area 1","Code":"xyz","StartTime":"09:30","EndTime":"13:40"},
{"ID":2,"Name":"Area 2","Code":"xyz","StartTime":"09:00","EndTime":"13:40"},
{"ID":3,"Name":"Area 3","Code":"xyz","StartTime":"10:30","EndTime":"14:40"},
{"ID":4,"Name":"Area 4","Code":null,"StartTime":"09:30","EndTime":"13:30"}]
I have retrieved model class value in NSMutableArray and displayed on TableView, Now I need to search name from model class, Below is my code, however its not been working.
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = searchController.searchBar.text;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF CONTAINS [cd] %#", searchString];
for (NSString *key in _arrAlreaList) {
NSArray *array = [_arrAlreaList valueForKey:key];
NSArray *tempArray = [array filteredArrayUsingPredicate:predicate];
if (tempArray.count > 0) {
[filteredArray addObjectsFromArray:tempArray];
[self.tblArea reloadData];
}
}
}
-(void)updateSearchResultsForSearchController:(UISearchController *)searchController {
NSString *searchString = searchController.searchBar.text;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.Name contains [c] %#", searchString];
NSArray *resultArray = [_arrAlreaList filteredArrayUsingPredicate:predicate];
NSLog(#"Result Array %#",resultArray);
}
Try This !!
I've array of strings like #"fog",#"foggy fod",#"computer",#"lap rop".
Now I've string string like #"i like fog" now I want to know if my string contains any of the words in my array. Please tell if any of the word in array exist in my string.
I've tried this so far
NSArray *array = [dictionary objectForKey:#"Keywords"];
NSLog(#"arry %#",array[0]);
int i=0;
for (i=0; i<[array count]; i++)
{
if([title containsString:array[i]])
{
break;
return true;
}
}
The for loop is exited before return true; is executed because of the break. Just remove the break:
for (i=0; i<[array count]; i++) {
if([title containsString:array[i]])
{
return true;
}
}
You may do it with a NSPredicate like this .
NSArray *array = #[#"fog",#"foggy fod",#"computer",#"lap rop"];
NSString *str = #"i like computer";
NSPredicate *predicate = [NSPredicate predicateWithFormat:#" %# contains[cd] SELF", str];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(#"filtered %#",filtered);
NSArray *arrData = [NSArray arrayWithObjects:
#"cloud,country,plant",
#"country,cloud,plant",
#"country,plant,cloud",
#"clouds,country,plant"
,#"country,clouds,plant",
nil];
From above NSArray, I want objects which having a word "cloud"
I tried below code
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(self beginswith %# OR self contains[CD] %#)",#"cloud",#",cloud"];
NSArray *arrResult = [arrData filteredArrayUsingPredicate:predicate];
But it's giving all 5 objects in arrResult. But I need only 3 (0,1,2) objects.
Try:
NSPredicate* predicate = [NSPredicate predicateWithBlock:^(NSString* string, NSDictionary* options){
NSArray* array = [string componentsSeparatedByString:#","];
return [array containsObject:#"cloud"];
}];
Try below code,
It will work,
NSPredicate *hsPredicate = [NSPredicate predicateWithBlock:^BOOL(id _Nonnull evaluatedObject, NSDictionary<NSString *,id> * _Nullable bindings) {
NSArray *sepretArray =[((NSString*)evaluatedObject) componentsSeparatedByString:#","];
NSPredicate *subPredicate = [NSPredicate predicateWithFormat:#"self == %#",#"cloud"];
return ([sepretArray filteredArrayUsingPredicate:subPredicate].count > 0);
}];
NSArray *arrResult = [arrData filteredArrayUsingPredicate:hsPredicate];
This one do the trick.But i don't know whether it is the efficient way of doing this.
NSArray *arrData = [NSArray arrayWithObjects:
#"cloud,country,plant",
#"country,cloud,plant",
#"country,plant,cloud",
#"clouds,country,plant"
,#"country,clouds,plant",
nil];
NSMutableArray *resArray = [[NSMutableArray alloc]init];
for(NSString *tempString in arrData)
{
NSArray *cache = [tempString componentsSeparatedByString:#","];
if([cache containsObject:#"cloud"])
{
[resArray addObject:tempString];
}
}
I have an application in which I have a UITextField where when I enter a character in UITextField it searches for any matches in my address book and if any match is found it display name and emailaddress of the respective person on a UITableView.
My problem is I am not able to search properly using predicate on my address book. When I enter any character it always displays the last record whether it matches my predicate or not.
This is my code. This is my textfieldchange method:
-(void)textFieldDidChange:(UITextField *)txtFld {
[self fetchAddressBook];
NSString *dictionaryKey = contact.name;
NSString *predicateString = contact.email;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K CONTAINS[cd] %#", dictionaryKey, predicateString];
listFiles = [NSMutableArray arrayWithArray:[self.namearray
filteredArrayUsingPredicate:predicate]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey:contact.name ascending:YES] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [listFiles sortedArrayUsingDescriptors:sortDescriptors];
if ([sortedArray count]>0)
{
tblView.hidden=FALSE;
txtSendAmount.hidden=TRUE;
txtSendMessage.hidden=TRUE;
[tblView reloadData];
}
else if ([sortedArray count]==0)
{
tblView.hidden=TRUE;
txtSendAmount.hidden=FALSE;
txtSendMessage.hidden=FALSE;
}
}
this is the code where i am fetching my email and name of person from address book and saving in an array
-(void)fetchAddressBook
{
CFErrorRef error = nil;
ABAddressBookRef allPeople = ABAddressBookCreateWithOptions(NULL,&error);
CFArrayRef allContacts = ABAddressBookCopyArrayOfAllPeople(allPeople);
CFIndex numberOfContacts = ABAddressBookGetPersonCount(allPeople);
NSMutableArray *testarray = [[NSMutableArray alloc] init];
NSMutableDictionary *addressdict = [[NSMutableDictionary alloc] init];
for(int i = 0; i < numberOfContacts; i++){
name = #"";
NSString* phone = #"";
email = #"";
contact = [[MContact alloc] init];
ABRecordRef aPerson = CFArrayGetValueAtIndex(allContacts, i);
ABMultiValueRef fnameProperty = ABRecordCopyValue(aPerson, kABPersonFirstNameProperty);
ABMultiValueRef lnameProperty = ABRecordCopyValue(aPerson, kABPersonLastNameProperty);
ABMultiValueRef phoneProperty = ABRecordCopyValue(aPerson, kABPersonPhoneProperty);
ABMultiValueRef emailProperty = ABRecordCopyValue(aPerson, kABPersonEmailProperty);
NSArray *emailArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailProperty);
NSArray *phoneArray = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(phoneProperty);
if (fnameProperty != nil) {
contact.name = [NSString stringWithFormat:#"%#", fnameProperty];
}
if (lnameProperty != nil) {
contact.name = [contact.name stringByAppendingString:[NSString stringWithFormat:#" %#", lnameProperty]];
}
if ([phoneArray count] > 0) {
if ([phoneArray count] > 1) {
for (int i = 0; i < [phoneArray count]; i++) {
phone = [phone stringByAppendingString:[NSString stringWithFormat:#"%#\n", [phoneArray objectAtIndex:i]]];
}
}else {
phone = [NSString stringWithFormat:#"%#", [phoneArray objectAtIndex:0]];
}
}
if ([emailArray count] > 0) {
if ([emailArray count] > 1) {
for (int i = 0; i < [emailArray count]; i++) {
contact.email = [contact.email stringByAppendingString:[NSString stringWithFormat:#"%#\n", [emailArray objectAtIndex:i]]];
}
}else {
contact.email = [NSString stringWithFormat:#"%#", [emailArray objectAtIndex:0]];
}
}
[self.emailnamearray addObject:contact];
self.namearray = [emailnamearray copy];
}
}
this is my cellforrowAtIndexPath method
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tblView dequeueReusableCellWithIdentifier:#"eventCell"];
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"eventCell"];
}
MContact *addressdict = [listFiles objectAtIndex:indexPath.row];
cell.textLabel.text=addressdict.name;
cell.detailTextLabel.text=addressdict.email;
return cell;
}
Your bug is there:
NSString *dictionaryKey = contact.name;
NSString *predicateString = contact.email;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K CONTAINS[cd] %#", dictionaryKey, predicateString];
The key should be #"name" or #"email", not a particular contact's name. Same for the sort descriptor.
i have contains list of countries. such as
countries_list = [NSMutableArray arrayWithObjects:#"Afghanistan",#"Albania",
#"Bolivia",#"Bulgaria",#"China", #"Estonia",#"France",#"Finland",
#"Greenland",#"Iceland",#"Japan", nil];
from this array i need to search such as Albania in sorted list all countries come which start with the alphabet Letter A and then sort Al so on and then i have to add these values in the uitableview..
i just need searching help me if any one can. thanks
NSMutableArray* containsAnother = [NSMutableArray array];
NSMutableArray* doesntAnother = [NSMutableArray array];
for (NSString* item in inputArray)
{
if ([item rangeOfString:#"Finland"].location != NSNotFound){
[containsAnother addObject:item];
NSLog(#"country is found..%#",containsAnother);
}else{
}
[doesntContainAnother addObject:item];
NSLog(#"country is not found..%#",doesntContainAnother);
}
NSLog(#"array is found..%#",containsAnother);
You can use NSPredicate class for this like this :-
NSMutableArray * array = [NSMutableArray array];
// Loop to fetch Team Names and store in NSMutableArray named array
for (NSDictionary *data in mySortedArray) {
NSString *TEAMNAME = #"TeamName";
NSString *countryName = #"Australia";
NSDictionary sortDictionary = [NSDictionary dictionaryWithObjectsAndKeys:countryName,TEAMNAME,nil];
[array addObject:sortDictionary];
}
NSSortDescriptor * ratingDescriptor =[[[NSSortDescriptor alloc] initWithKey:TEAMNAME ascending:YES] autorelease];
NSArray * descriptors = [NSArray arrayWithObjects:ratingDescriptor, nil];
mySortedArray = (NSMutableArray *)[array sortedArrayUsingDescriptors:descriptors];
And it is done. Hope it helps :)
try using NSPredicate predicateWithFormat: method
countries_list = [NSMutableArray arrayWithObjects:#"Afghanistan",#"Albania",#"Bolivia",#"Bulgaria",#"China", #"Estonia",#"France",#"Finland", #"Greenland",#"Iceland",#"Japan", nil];
NSPredicate *predicte = [NSPredicate predicateWithFormat:
#"Self beginswith[c] %#", #"Albania"];
NSArray *filteredArray = [countries_list filteredArrayUsingPredicate:predicte];
NSLog([filteredArray description]);