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);
Related
I want to create a table view which is scrollable both horizontally and vertically. I can do this by taking values myself. But I want to take the values from json. I am using model class and my json values are like this:
[
{
"cid": 109,
"iid": 10653,
"yr": 1994,
"val": "15.4311527806175"
},
{
"cid": 109,
"iid": 7872,
"yr": 1999,
"val": "8.84575553637328"
},
{
"cid": 109,
"iid": 7872,
"yr": 1998,
"val": "6.18441582677751"
},
I want my first column to be fixed when scrolling horizontally and first row to be fixed when I scroll it vertically. First column should have iid. first row should have yr and data should have val.
I am using XCMltisortTableView, ASIHttpRequest and SBJson.
I am getting the header value and left column value. How can I get the data corresponding to the yr and iid in proper column?
My code for val in requestFinished method is as follows:
rightTableData = [NSMutableArray arrayWithCapacity:mainTableData.count];
NSMutableArray *right = [NSMutableArray arrayWithCapacity:mainTableData.count];
for (int i = 0; i < mainTableData.count; i++)
{
// Model *model = [mainTableData objectAtIndex:i];
NSMutableArray *array = [NSMutableArray arrayWithCapacity:mainTableData.count];
for (int j = 0; j < headData.count; j++)
{
Model *model = [mainTableData objectAtIndex:j];
if([headData isEqual: #"2000"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2001"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2002"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2003"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else if([headData isEqual: #"2004"])
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
else
{
[array addObject:[NSString stringWithFormat:#"%#", model.val]];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
I'm totally new and would a appreciate any answers and any suggestions. Please do reply.
Thanks!
After trying for a long time I got the result using the code below:
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];
headData = [[NSMutableArray alloc] init];
NSMutableArray *head = [[NSMutableArray alloc] init];
leftTableData = [[NSMutableArray alloc] init];
NSMutableArray *left = [[NSMutableArray alloc] init];
rightTableData = [[NSMutableArray alloc]init];
for (NSMutableArray *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [[dictionary valueForKey:#"cid"]intValue];
model.iid = [[dictionary valueForKey:#"iid"]intValue];
model.yr = [[dictionary valueForKey:#"yr"]intValue];
model.val = [dictionary valueForKey:#"val"];
[mainTableData addObject:model];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
}
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
headData = [[orderedSet array] mutableCopy];
NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];
//remove duplicate enteries from header array
[leftTableData addObject:arrLeft];
NSMutableArray *right = [[NSMutableArray alloc]init];
for (int i = 0; i < arrLeft.count; i++)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int j = 0; j < headData.count; j++)
{
/* NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
Hope it helps others.
In my code i'm sorting contacts using lastname,It shows error with LastName is null.How to sort null lastname into hash symbol.
Here my code
-(void)updateView:(NSArray*)contactsArray{
[self.dataArray removeAllObjects];
[self.sections removeAllObjects];
[self.dataArray addObjectsFromArray:contactsArray];
BOOL found;
for (Contact *contact in self.dataArray)
{
NSString *c = [[contact.lastName substringToIndex:1] uppercaseString];
found = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
}
}
// Loop again and sort the books into their respective keys
for (Contact *contact in self.dataArray)
{
[[self.sections objectForKey:[[contact.lastName substringToIndex:1] uppercaseString]] addObject:contact];
}
// Sort each section array
for (NSString *key in [self.sections allKeys])
{
[[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"lastName" ascending:YES]]];
}
NSLog(#"Check %#",contactsArray);
[self.tableView reloadData];
}
Everywhere that you do
[contact.lastName substringToIndex:1];
Is unsafe if you might possibly have an empty string because the substring request will always throw a range exception. You need to change that code.
The simple option is to check the length beforehand and if it's too short substitute some other known value so that all of the empty last names are grouped together.
I have two NSMutableArrays: searchResults and searchResultsDetails. I sort searchResults with NSPredicate, and I want searchResultsDetails to be sorted based on which objects were removed from searchResults with the NSPredicate.
For example, let's say searchResults originally contains 1,2,3,4,5 and searchResultsDetails originally contains A,B,C,D,E. So after sorting it with NSPredicate, searchResults contains 1,2,5, and I want searchResultsDetails to contain A,B,E. How can I accomplish this?
This is the code I am using to sort the first array.
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"self CONTAINS %#",
searchText];
self.searchResults = [self.lines filteredArrayUsingPredicate:resultPredicate];
NSMutableArray *firstArray = [[NSMutableArray alloc] initWithObjects:#"ashu",#"toremove",#"ashuabc",#"toremove",#"ashu12345", nil];
NSMutableArray *descriptionArray = [[NSMutableArray alloc] initWithObjects:#"description for ashu",#"description for non ashu",#"description for ashuabc",#"description for nopnashu",#"description for ashu12345", nil];
NSMutableArray *removedIndexArray = [[NSMutableArray alloc] init];
NSMutableArray *sortedArray = [[NSMutableArray alloc] init];
for (int i = 0; i < [firstArray count]; i++) {
NSString *tempStr = [firstArray objectAtIndex:i];
if ([tempStr rangeOfString:#"ashu"].location == NSNotFound) {
[removedIndexArray addObject:[NSString stringWithFormat:#"%d",i]];
} else {
[sortedArray addObject:tempStr];
}
}
for (int j = 0; j < [removedIndexArray count]; j++) {
[descriptionArray removeObjectAtIndex:[[removedIndexArray objectAtIndex:j] integerValue]];
}
NSLog(#"%#",descriptionArray);
NSLog(#"Sorted array is :: %#",sortedArray);
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];
}
}
I have three arrays. They are name, birthdates and remaining days like below:
name birthdate remaining
"Abhi Shah", "01/14", 300
"Akash Parikh", "12/09/1989", 264
"Anand Kapadiya", "12/01", 256
"Annabella Faith Perez", "03/02", 347
"Aysu Can", "04/14/1992", 25
"Chirag Pandya" "10/07/1987" 201
I want to rearrange the remaining days array into ascending order,
but at the same time name and birthdate should also get reordered in the same way.
See this example below:
name birthdate remaining
"Aysu Can", "04/14/1992", 25
"Chirag Pandya" "10/07/1987" 201
"etc..."
use NSMutableDictionary to store data to NSMutableArray
NSMutableArray *array=[[NSMutableArray alloc]init];
for (int i=0; i<totalRows; i++)
{
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
[dic setValue:[array_1 objectAtIndex:i] forKey:#"names"];
[dic setValue:[array_2 objectAtIndex:i] forKey:#"birthdate "];
[dic setValue:[array_3 objectAtIndex:i] forKey:#"remanning"];
[array addObject:dic];
[dic release];
}
here after you arrange name array,use search option to use name not use index and
use NSPredicate search data in NSMutableArray
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"names matches[cd] %#", name];
NSArray *result = [array filteredArrayUsingPredicate:predicate];
NSMutableDictionary *dict = [[[result objectAtIndex:0] mutableCopy] autorelease];
NSLog(#"%#",dict);// result
self.arrayForRows = [[NSMutableArray alloc]init];
NSMutableArray *arrayForNames = [[NSMutableArray alloc]initWithObjects:#"Abhi Shah",#"Akash",#"Nagavendra",#"Ramana",#"Simhachalam", nil];
NSMutableArray *arrayForBirthDates = [[NSMutableArray alloc]initWithObjects:#"01/14/94",#"01/14",#"11/07/87",#"12/07/89",#"23/08/91", nil];
NSMutableArray *arrayForRemaining = [[NSMutableArray alloc]initWithObjects:#"200",#"320",#"32",#"450",#"14", nil];
for (int i=0; i<arrayForBirthDates.count; i++)
{
NSMutableDictionary *tempDicts = [[NSMutableDictionary alloc]init];
[tempDicts setObject:[arrayForNames objectAtIndex:i] forKey:#"names"];
[tempDicts setObject:[arrayForBirthDates objectAtIndex:i] forKey:#"birth"];
[tempDicts setObject:[NSNumber numberWithInt:[[arrayForRemaining objectAtIndex:i] intValue]] forKey:#"remaining"];
[self.arrayForRows addObject:tempDicts];
}
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"remaining" ascending:YES];
[self.arrayForRows sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Use this in tableView listing
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arrayForRows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifer = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifer];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
}
cell.textLabel.text = [[self.arrayForRows objectAtIndex:indexPath.row] valueForKey:#"names"];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
once try like this it'l help you,
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setObject:#"rahul" forKey:#"name"];
[dict setObject:#"10" forKey:#"value"];
NSMutableDictionary *dict1=[[NSMutableDictionary alloc]init];
[dict1 setObject:#"ttt" forKey:#"name"];
[dict1 setObject:#"6" forKey:#"value"];
NSMutableArray *ar=[[NSMutableArray alloc]init];
[ar addObject:dict];
[ar addObject:dict1];
NSSortDescriptor *Sorter = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
[ar sortUsingDescriptors:[NSArray arrayWithObject:Sorter]];
NSLog(#"---%#",ar);
Put each row into a dictionary, and out those dictionaries into an array. Then sort your away using a predicate or sort block. If you want an array containing just the sorted names for example, you could use [ array valueForKeyPath:#"name" ]
Array looks like:
[
{ #"name" : ...,
#"birthdate" : ...birthdate...,
#"remaining" : ...days remaining... } ,
{...},
{...}
]
such as your MutableArray is a Dictionarys array , you can use sortUsingComparator
to sort the array
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int a = [(NSNumber *)[(NSDictionary *)obj1 objectiveForKey: #"remanning"] intValue];
int b = [(NSNumber *)[(NSDictionary *)obj2 objectiveForKey: #"remanning"] intValue];
if (a < b) {
return NSOrderedAscending;
}
else if(a == b)
{
return NSOrderedSame;
}
return NSOrderedDescending;
}];
For example , I have a test :
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#(30),#(20),#(5),#(100), nil];
[array sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int a = [(NSNumber *)obj1 intValue];
int b = [(NSNumber *)obj2 intValue];
if (a < b) {
return NSOrderedAscending;
}
else if(a == b)
{
return NSOrderedSame;
}
return NSOrderedDescending;
}];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"%# , %d",obj,idx);
}];
then the output is :