Sorting many labels in a tableView - ios

I have a custom UITableviewCell which contains a few UILabels on them. The data is received from web services and I'd like to sort them based on one of the UILabels. The data received is stored in an array. How can I sort them?
Thanks! :)
Code written to add data to the cells from a BO:
cells.head.text = [[self.messageStore objectAtIndex:indexPath.section] subject];
cells.subhead.text = [[self.messageStore objectAtIndex:indexPath.section] messageli];
cells.signature.text=[AppConstants getUsername];
cells.viewCount.text = [NSString stringWithFormat:#"%# Views",[[self.messageStore objectAtIndex:indexPath.section] viewsCount]];
cells.interested.text= [[self.messageStore objectAtIndex:indexPath.section] interestedCount];
cells.date.text = [[self.messageStore objectAtIndex:indexPath.section] creationDate];
[cells.image1 sd_setImageWithURL:[NSURL URLWithString:[[self.messageStore objectAtIndex:indexPath.section] imageURL]] placeholderImage:[UIImage imageNamed:#"no_photo.png"]];
cells.editZButton.hidden = NO;
cells.editZButton.tintColor = [UIColor whiteColor];
cells.deleteZButton.hidden = NO;
cells.amount.text = [NSString stringWithFormat:#"$ %#",[[self.messageStore objectAtIndex:indexPath.section] priceAmount]]; cells.editZButton.tag = indexPath.section;
cells.deleteZButton.tag = indexPath.section;
[cells.editZButton addTarget:self action:#selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[cells.deleteZButton addTarget:self action:#selector(deleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];

You can sort the data using the predicate
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"Your_Key ==%#",Your_Value_For_Key];
NSArray *array=[Your_Array_Of_Data filteredArrayUsingPredicate:predicate];

Since you didn't gave us the exact array to be sorted, I'm assuming its just a simple NSArray of strings.
You can use NSSortDescriptor to sort NSArray as below
NSArray *arr = [[NSArray alloc] initWithObjects:#"Sam", #"John", #"Andrew", nil];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"self" ascending:NO];
NSArray *sortedArray = [arr sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Then reload your tableview with the "sortedArray".

Below one is generic method, you can try.
- (NSMutableArray*)sortArray:(NSMutableArray*)dataArray filterKeyName:(NSString*)KeyName ascending:(BOOL)isAscending{
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:KeyName ascending:isAscending];
[dataArray sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
return dataArray; // Sorted data array..
}

Related

adjust order of one array based on the order of another array that was sorted

I have two tables, one table for usernames, and one table for scores. I populate those tables with two arrays. The tables need to be in descending order based on the scores. I sort the array with the scores in it, but I am not sure how I can arrange the usernames to stick with their score, they are in a separate array, and a separate table from the scores table. Here is my code:
dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [dictionary allKeys];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: #selector(compare:)];
I need the sortedFirstArray values to stick with their respective sortedSecondArray values in terms of their order in each of their arrays.
UPDATE
My code attempting to do the sorting:
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
entries = [NSMutableArray new];
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
[tableData addObject:[object valueForKey:#"username"]];
[matchesForUser addObject:[object valueForKey:#"matches"]];
NSMutableDictionary* entry = [NSMutableDictionary new];
entry[#"username"] = [object valueForKey:#"username"];
entry[#"matches"] = [object valueForKey:#"matches"];
[entries addObject:entry];
//transfer = entries;
}
transfer = [entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
NSDate *first = [a objectForKey:#"matches"];
NSDate *second = [b objectForKey:#"matches"];
NSLog(first);
NSLog(second);
return [first compare:second];
}];
//dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
//sortedFirstArray = [dictionary allKeys];
//sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
//sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: #selector(compare:)];
[_tableView reloadData];
[_tableViewScore reloadData];
}else{
NSLog([error description]);
}
NSLog(#"***tabledata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[tableData count]]);
NSLog(#"***matchesdata***");
NSLog([NSString stringWithFormat:#"%lu", (unsigned long)[matchesForUser count]]);
});
}];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(tableView.tag == 1) {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
cell.textLabel.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
cell.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.layoutMargins = UIEdgeInsetsZero;
cell.preservesSuperviewLayoutMargins = NO;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
UILabel *contentV = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 230, 44)];
contentV.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
contentV.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
contentV.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.contentView.layoutMargins = UIEdgeInsetsZero;
NSString *username2 = [[transfer objectAtIndex:indexPath.row] valueForKey:#"username"];
NSLog(#"***username***");
NSLog(username2);
contentV.text = username2;
[cell.contentView addSubview:contentV];
return cell;
}
else {
static NSString *simpleTableIdentifier = #"SimpleTableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
cell.textLabel.font = [UIFont fontWithName:#"HelveticaNeue-Bold" size:16.0];
cell.textLabel.textColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
cell.backgroundColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
cell.textLabel.textAlignment = NSTextAlignmentCenter;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
NSString *matchAmount = [[transfer objectAtIndex:indexPath.row] valueForKey:#"matches"];
NSLog(#"***matchamount***");
NSLog(matchAmount);
cell.textLabel.text = matchAmount;
return cell;
}
}
Instead of having two separate arrays and going trough the trouble of sorting one of them directly and try to figure out which entries of the other correspond to which in the sorted one, you should instead keep the paired entries of both arrays together in one entity (dictionary or instance of a custom class), and group those in your (single) array:
The actual property names etc. will vary for your code, but the general idea is like this:
self.entries = [NSMutableArray new];
for (int i=0; i < userNameArray.count; i++){
NSMutableDictionary* entry = [NSMutableDictionary new];
entry["userName"] = [userNameArray objectAtIndex: i];
entry["score" ] = [scoreArray objectAtIndex: i];
// ^ TODO: Make sure scoreArray has at least as many elements
// as userNameArray!
[self.entries addObject: entry];
}
self.entries = [self.entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
NSDate *first = [a objectForKey:"score"];
NSDate *second = [b objectForKey:"score"];
return [first compare:second];
}];
// (...)
UITableViewCell* tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath}) indexPath
{
NSDictionary* entry = [self.entries objectAtIndex: indexPath.row];
if (tableView == self.userNameTableView) {
// (dequeue user cell...)
cell.titleLabel.text = [entry objectForKey: "userName"];
return cell
}
else{
// (dequeue score cell...)
cell.titleLabel.text = [entry objectForKey: "score"];
return cell
}
}
Credit goes to NicolasMiari for helping me figure most of this out. Something weird was happening with the way the comparison was being made - and it was producing an unsorted result. This is how I sorted:
NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:#"matches" ascending:NO selector:#selector(localizedStandardCompare:)];
NSArray *entrieshold = [entries sortedArrayUsingDescriptors:#[descriptor]];
transfer = [entrieshold copy];
It seemed like the most important thing for me was selector:#selector(localizedStandardCompare:). My use of copy also may be important...but I don't think so.

How to display searchresults in alphabetical order in ios

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.

Issue with deleting rows after adding section header to uitableview

Before adding section headers to one of my tables in my app, I was able to delete rows using the commitEditingStyle function without any issues. I decided to implement section headers to make it easier for the user to view items added to the table by date. This functionality works fine. I was having an issue with deleting rows after implementing the section headers but thanks to help from the good folks on stackoverflow the problem was partially resolved. After some testing I've realized that if the rows are in the same section and I try to delete more than one row in sequence beginning with the top row in the section, the top row deletes fine but trying to delete the second row causes the app to crash. If I delete all rows in sequence other than the first row and then delete the first row last, it works fine. Xcode doesn't indicate why it crashes in the debug log.
Here is the code for the cellForRowAtIndexPath function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
AgendaCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[AgendaCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
NSString *strDate = [dateArray objectAtIndex:indexPath.section];
NSMutableArray *dateSection = [tempDict objectForKey:strDate];
NSManagedObject *object = [dateSection objectAtIndex:indexPath.row];
cell.sessionNameLabel.text = [object valueForKey:#"sessionname"];
cell.sessionNameLabel.textColor = [UIColor blueColor];
cell.sessionDateLabel.text = [object valueForKey:#"sessiondate"];
cell.sessionDateLabel.textColor = [UIColor brownColor];
cell.sessionTimeLabel.text = [object valueForKey:#"sessiontime"];
cell.sessionTimeLabel.textColor = [UIColor brownColor];
return cell;
}
Here is the code for my table refresh function:
- (void) refreshTable
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Sessnotes" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"agenda == 'Yes'"]];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sessiondate" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSArray *results = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
[self.refreshControl endRefreshing];
self.objects = results;
if (results.count == 0) {
NSString *message = #"You have not added any sessions to your planner.";
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:#"Notification"
message:message
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil,nil];
[alertView show];
}
else if (results.count > 0){
tempDict = nil;
tempDict = [[NSMutableDictionary alloc] init];
NSString *strPrevDate= [[results objectAtIndex:0] valueForKey:#"sessiondate"];
NSLog(#"strPrevDate value is: %#", strPrevDate);
NSString *strCurrDate = nil;
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
//Add the Similar Date data in An Array then add this array to Dictionary
//With date name as a Key. It helps to easily create section in table.
for(int i=0; i< [results count]; i++)
{
strCurrDate = [[results objectAtIndex:i] valueForKey:#"sessiondate"];
if ([strCurrDate isEqualToString:strPrevDate])
{
[tempArray addObject:[results objectAtIndex:i]];
}
else
{
[tempDict setValue:[tempArray copy] forKey:strPrevDate];
strPrevDate = strCurrDate;
[tempArray removeAllObjects];
[tempArray addObject:[results objectAtIndex:i]];
}
}
//Set the last date array in dictionary
[tempDict setValue:[tempArray copy] forKey:strPrevDate];
NSArray *tArray = [tempDict allKeys];
//Sort the array in ascending order
dateArray = [tArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
}
[self.tableView reloadData];
}
Here is the code for the commitEditingStyle function:
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
NSManagedObject *object = [self.objects objectAtIndex:indexPath.row];
NSManagedObjectContext *context = [self managedObjectContext];
[context deleteObject:[context objectWithID:[object objectID]]];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSMutableArray *array = [self.objects mutableCopy];
[array removeObjectAtIndex:indexPath.row];
self.objects = array;
[tableView reloadData];
}
}
A couple things up front. I wouldn't make fetch requests everytime you want to reload the tableview. You should look at NSFetchedResultsController. It will automatically bind data to your tableview and do the refreshes for you based on updates coming from either the same NSManagedObjectContexts or messages about updates from other contexts and batch them for you as well.
To answer your original question. I would try to remove the object from the array first and then delete the NSManagedObject and then you can use some tableview trickery:
NSManagedObject *managedObject = self.array[indexPath.row];
[self.array removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation: UITableViewRowAnimationAutomatic];
[context deleteObject:managedObject];
I could be wrong but it's possible you're failing to fullfil a fault. Hope that helps.

get IndexPath in a Sorted Array

I am getting values which are sorted from a plist and displaying them in a tableview. I am providing the capability of entering a custom category which will be written to plist. But I want that to be Inserted in the sorted alphabetical order. Can someone suggest me how to get the indexpath of the row where it has to be inserted. I have used the following code where the custom entry will be inserted at the 0 location
NSInteger section = 0;
NSInteger row = 0;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
NSDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setValue:newCategoryName forKey:#"name" ];
[categoryDictionary setValue:#"custom.png" forKey:#"image"];
[[self categoriesArray]insertObject:categoryDictionary atIndex:row];
[[self categoriesArray] writeToFile:[self dataFilePath] atomically:YES];
NSArray *indexPathsToInsert = [NSArray arrayWithObject:indexPath];
[[self tableView]insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:UITableViewRowAnimationRight];
[self.categoriesArray writeToFile:[self dataFilePath] atomically:YES];
Try
NSMutableDictionary *categoryDictionary = [NSMutableDictionary dictionary];
[categoryDictionary setObject:newCategoryName forKey:#"name" ];
[categoryDictionary setObject:#"custom.png" forKey:#"image"];
//Add new category to array
[self.categoriesArray addObject:categoryDictionary];
//Sort Array
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
[self.categoriesArray sortUsingDescriptors:#[sortDescriptor]];
//Write array to plist
[self.categoriesArray writeToFile:[self dataFilePath] atomically:YES];
NSInteger section = 0;
//Get the index of saved Category item
NSInteger row = [self.categoriesArray indexOfObject:categoryDictionary];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationRight];
In your table you will get section and row using following
NSInteger section = indexPath.section;
NSInteger row = indexPath.row;
if you have an array of sortable items, you can use this code snippet as help:
NSArray *sortedArray = #[#"a" , #"b", #"d", #"c", #"f"];
sortedArray = [sortedArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
NSLog(#"%#", sortedArray);
int c = [sortedArray indexOfObject:#"c"];
NSLog(#"%d", c);
Logs ->
(
a,
b,
c,
d,
f
)
2
so you first insert your object in the "toSort" array and then get the index of it ;)

how to change order of NSMutable array in same way another mutable arrays get changed

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 :

Resources