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]);
Related
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];
}
}
- (void)loadData: (NSMutableArray *)myMutableArray {
self.myMutableDict = [[NSMutableDictionary alloc] init];
for (NSString *str in myMutableArray) {
NSString *key = [str substringToIndex:1];
NSLog(#"Key: %#", key);
NSLog(#"str: %#", str);
if ([self.myMutableDict objectForKey:key]) {
NSMutableArray *list = (NSMutableArray *)[self.myMutableDict objectForKey:key];
[list addObject:str];
[self.myMutableDict setObject:list forKey:key];
} else {
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:str, nil];
[self.myMutableDict setObject:list forKey:key];
}
}
[self.tblAlphabeticalOrder reloadData];
}
Your mutable array has only one very long string with lots of commas in it. You need to quote each item separately:
NSArray *array = [[NSArray alloc] initWithObjects:#"Shyam", #"Ram", #"Hari", #"Gita", .....
This question already has answers here:
Avoiding "NSArray was mutated while being enumerated"
(11 answers)
Closed 7 years ago.
I want to remove object from array when the name is same. How to do this? Thanks in advance. Here is my code
NSString *name1;
NSString *name2;
NSArray *copyArray = [uniqueArraySort copy];
for (NSMutableDictionary *dict1 in copyArray) {
for (NSDictionary *dict2 in uniqueArraySort) {
name1 = [dict1 valueForKey:#"name"];
name2 = [dict2 valueForKey:#"name"];
if ([name1 isEqualToString:name2]) {
NSLog(#"%#",uniqueArraySort);
[uniqueArraySort removeObject:dict2];
NSLog(#"%#",uniqueArraySort);
}
}
}
And when I compile I get this error
<__NSArrayM: 0x7fea39804f40> was mutated while being enumerated.'
Try something like this... I assume value for key "name" might be a string.
NSSet *set = [NSSet setWithArray:[uniqueArraySort valueForKey:#"name"]];
NSMutableArray *array = [NSMutableArray new];
for (NSString* value in set.allObjects) {
NSArray *filteredArray = [uniqueArraySort filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"name = %#", value]];
if(filteredArray.count > 0)
[array addObject:[filteredArray firstObject]];
}
return array;
UPDATE : On second thought, I found that code above is still too much. You can do it at O(n) using hashtable.
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithCapacity:uniqueArraySort.count];
for(NSDictionary *item in uniqueArraySort)
{
NSString *name = [item objectForKey:#"name"];
if([dictionary objectForKey:name] == nil)
{
[dictionary setObject:item forKey:name];
}
}
return dictionary.allValues;
What you need to do is create a separate mutable array. Something like this:
NSMutableArray *itemsToDelete = [NSMutableArray array];
NSMutableArray *copyArray = [uniqueArraySort mutableCopy];
for (NSMutableDictionary *dict1 in copyArray) {
for (NSDictionary *dict2 in uniqueArraySort) {
name1 = [dict1 valueForKey:#"name"];
name2 = [dict2 valueForKey:#"name"];
if ([name1 isEqualToString:name2]) {
NSLog(#"%#",uniqueArraySort);
[itemsToDelete addObject:dict2];
NSLog(#"%#",uniqueArraySort);
}
}
}
[copyArray removeObjectsInArray:itemsToDelete];
Also, I'm not sure what you are doing with uniqueArraySort but you might need to make that an NSMutableArray if you plan on using it after.
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 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 :