Hi in my application I have a to search few elements and the result have to show in tableview. For example if the elements are
NS1,NSE2,NAse3,NWe3,Nxw,NB22 like this if I search for N then the data have to display as such below
NAse3
NB22
NSE2
NS1
NWe3
Nxw.
Please let me know how to implement this.
Now I am using the below code I am performing the search.
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
if([array count]!=0){
array2=[[NSMutableArray alloc]initWithCapacity:0 ];
for(NSMutableDictionary *data in array){
r = [[data objectForKey:#"Product"] rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound){
if(r.location== 0)
[array2 addObject:data];
}
}
}
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
if([array count]!=0)
{
array2=[[NSMutableArray alloc]initWithCapacity:0];
for(NSMutableDictionary *data in array)
{
r = [[data objectForKey:#"Product"] rangeOfString:searchBar.text options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
if(r.location== 0)
[array2 addObject:data];
}
}
NSSortDescriptor *sortDis = [[NSSortDescriptor alloc] initWithKey:#"Product"
ascending:YES selector:#selector(localizedStandardCompare:)];
[array2 sortUsingDescriptors:[NSArray arrayWithObject:sortDis]];
}
}
try this to sort your results:
array2 = [array2 sortedArrayUsingComparator:^(id a, id b) {
return [a compare:b options:NSNumericSearch];
}];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"your Key"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingDescriptors:sortDescriptors];
Using custom comparator-methods is possible Have a look at the documentation.
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];
}
}
I need some help indexing a UITableView, dividing the data in alphabetic sections. The data model is from a core data graph.
I have the index (A-Z), loaded ok, and the section headers are correct. The issue is that the data is not sorted correctly (i.e. alphabetic).
There is an entity attribute in the model that is an alphabetic index. I've looked at the sqlite file and that is ok.
Here are pieces of relevant code. Please help me understand what I'm missing or messing :)
- (void)viewDidLoad {
[super viewDidLoad];
sectionArray = [[NSArray alloc] init];
self.collation = [UILocalizedIndexedCollation currentCollation];
if (languageKey == 0) {
sectionArray = [NSArray arrayWithArray:[#"|α,ά|β|γ|δ|ε,έ|ζ|η,ή|θ|ι,ί|κ|λ|μ|ν|Ξ|ο,ό|π|ρ|σ|τ|υ,υ|φ|χ|ψ|ω,ώ|#"
componentsSeparatedByString:#"|"]];
} else {
sectionArray = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
}
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription
entityForName:#"WordEntity" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
[request setPredicate:[self predicate]];
[request setIncludesSubentities:NO];
filteredWordsArray = [[NSMutableArray alloc] init];
self.searchResults = [NSMutableArray arrayWithCapacity:[[self.fetchedResultsController fetchedObjects] count]];
self.searchDisplayController.searchResultsTableView.rowHeight = wordTable.rowHeight;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.searchResults count];
}
else
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"WordCell";
UITableViewCell *cell = (UITableViewCell *)[self.wordTable dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
WordEntity *word = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
word = [self.searchResults objectAtIndex:indexPath.row];
count = self.searchResults.count;
self.numberWordsLabel.text = [NSString stringWithFormat:#"%lu", (unsigned long)count];
} else {
word = [self.fetchedResultsController objectAtIndexPath:indexPath];
self.numberWordsLabel.text = [NSString stringWithFormat:#"%lu", (unsigned long)fullCount];
}
if (languageKey == 0) {
cell.textLabel.text = word.greekText;
cell.detailTextLabel.text = word.englishText;
} else {
cell.textLabel.text = word.englishText;
cell.detailTextLabel.text = word.greekText;
}
return cell;
}
/*
Section-related methods: Retrieve the section titles and section index titles from the collation.
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
long languageKey = [defaults integerForKey:DEFAULT_KEY_LANGUAGE_NUMBER];
long count = 0;
if (languageKey == 0) {
count = 24;
} else {
count = 26;
}
return count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [sectionArray objectAtIndex:section];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return sectionArray;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [collation sectionForSectionIndexTitleAtIndex:index];
}
- (NSFetchedResultsController *)fetchedResultsController {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] init];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
long languageKey = [defaults integerForKey:DEFAULT_KEY_LANGUAGE_NUMBER ];
if (languageKey == 0) {
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"greekKey" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
// sectionTitleString = #"greekKey";
} else {
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"englishKey" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)];
// sectionTitleString = #"englishKey";
}
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"greekKey" cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
/*
-(NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
collation = [UILocalizedIndexedCollation currentCollation];
NSInteger sectionCount = [[collation sectionTitles] count]; //section count is from sectionTitles and not sectionIndexTitles
NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
//create an array to hold the data for each section
for(int i = 0; i < sectionCount; i++)
{
[unsortedSections addObject:[NSMutableArray array]];
}
//put each object into a section
for (id object in array)
{
NSInteger index = [collation sectionForObject:object collationStringSelector:selector];
[[unsortedSections objectAtIndex:index] addObject:object];
}
sections = [NSMutableArray arrayWithCapacity:sectionCount];
//sort each section
for (NSMutableArray *section in unsortedSections)
{
[sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
}
return sections;
}
*/
This is what I'm seeing:
Try adding a sort descriptor to your NSFetchRequest...
NSSortDescriptor *sortDescriptorSecondary = [[NSSortDescriptor alloc]
initWithKey:#"word" ascending:YES];
[request setSortDescriptors:#[sectionArray, sortDescriptorSecondary]];
Note that when you are using sections in your table view, you must always sort by section first and then other criteria.
UPDATE
In a little more detail...
Private properties to include:
#property (nonatomic, strong) NSArray *sectionArray;
Fetch request to include:
// Declare sort descriptors
NSArray *requestSortDescriptors = nil;
NSSortDescriptor *sortDescriptorPrimary = nil;
NSSortDescriptor *sortDescriptorSecondary = nil;
// Set sort descriptors...
// Primary sort descriptor is your section array - sort by sections first.
sortDescriptorPrimary = [NSSortDescriptor sortDescriptorWithKey:self.sectionArray ascending:YES];
// Secondary sort descriptor is your entity attribute `word` - sort by fetched data second.
sortDescriptorSecondary = [NSSortDescriptor sortDescriptorWithKey:#"word" ascending:YES];
// Set sort descriptor array
requestSortDescriptors = #[sortDescriptorPrimary, sortDescriptorSecondary];
// Apply sort descriptors to fetch request
[request setSortDescriptors:requestSortDescriptors];
Hope this assists, let me know if you require further explanation.
SECOND UPDATE
I neglected to mention how to propagate the section data.
Personally, for data that is to be displayed in a TVC with section headers, for each entity I define an entity attribute that I always for simplicity call sectionIdentifier.
Then as a part of my methods to persist data, I ensure "section" data is allocated to this attribute sectionIdentifier (e.g. in your example A, B, C, etc).
In your case however, and for this particular example, you have established a local variable called sectionArray in your viewDidLoad TVC lifecycle method.
Working with your code in mind, I suggest the following (per above)...
Private properties to include:
#property (nonatomic, strong) NSArray *sectionArray;
Also working with your code in mind, I suggest the following (new)...
Alter your TVC lifecycle method viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
self.sectionArray = nil;
self.collation = [UILocalizedIndexedCollation currentCollation];
if (languageKey == 0) {
self.sectionArray = [NSArray arrayWithArray:[#"|α,ά|β|γ|δ|ε,έ|ζ|η,ή|θ|ι,ί|κ|λ|μ|ν|Ξ|ο,ό|π|ρ|σ|τ|υ,υ|φ|χ|ψ|ω,ώ|#"
componentsSeparatedByString:#"|"]];
} else {
self.sectionArray = [NSArray arrayWithArray:[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
}
// I have commented out code following because I cannot see where you are using it.
// Does the compiler not throw up warnings for this fetch request?
//
// NSManagedObjectContext *context = [self managedObjectContext];
// NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"WordEntity" inManagedObjectContext:context];
// NSFetchRequest *request = [[NSFetchRequest alloc] init];
// [request setEntity:entityDescription];
// [request setPredicate:[self predicate]];
// [request setIncludesSubentities:NO];
filteredWordsArray = [[NSMutableArray alloc] init];
self.searchResults = [NSMutableArray arrayWithCapacity:[[self.fetchedResultsController fetchedObjects] count]];
self.searchDisplayController.searchResultsTableView.rowHeight = wordTable.rowHeight;
}
Also working with your code in mind, I suggest the following (new)...
Alter your NSFetchedResultsController getter method:
- (NSFetchedResultsController *)fetchedResultsController {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
long languageKey = [defaults integerForKey:DEFAULT_KEY_LANGUAGE_NUMBER ];
// Set up fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest fetchRequestWithEntityName:#"WordEntity"];
[fetchRequest setPredicate:[self predicate]];
[fetchRequest setIncludesSubentities:NO];
// Declare sort descriptor variables
NSArray *requestSortDescriptors = nil;
NSSortDescriptor *sortDescriptorPrimary = nil;
NSSortDescriptor *sortDescriptorSecondary = nil;
// Set sort descriptors...
// Primary sort descriptor is your section array - sort by sections first.
sortDescriptorPrimary = [NSSortDescriptor sortDescriptorWithKey:self.sectionArray
ascending:YES];
// Secondary sort descriptor is your entity attribute - sort by fetched data second.
if (languageKey == 0) {
sortDescriptorSecondary = [NSSortDescriptor sortDescriptorWithKey:#"greekKey"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)];
// sectionTitleString = #"greekKey";
} else {
sortDescriptorSecondary = [NSSortDescriptor sortDescriptorWithKey:#"englishKey"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)];
// sectionTitleString = #"englishKey";
}
// Set sort descriptor array - section first, then table view data
requestSortDescriptors = #[sortDescriptorPrimary, sortDescriptorSecondary];
// Apply sort descriptors to fetch request
[fetchRequest setSortDescriptors:requestSortDescriptors];
// Your sectionNameKeyPath in your FRC is self.sectionArray (this may be incorrect - try)
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:self.sectionArray
cacheName:nil];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
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 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]);
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 :