Extract NSArray of dictionary in iOS - ios

I am having a response data as below .I have an array populated by dictionaries, and I need to sort last two values from each index of multi dimensional array.
This is my array:
arrayListstatus
(
{
"Applicant_FirstName" = "";
"Applicant_LastName" = "";
"Application_ID" = test;
"Application_Status" = "";
},
{
"Applicant_FirstName" = John;
"Applicant_LastName" = Doe;
"Application_ID" = 0002;
"Application_Status" = Recertify;
}
)
Here is my code:
- (NSArray *)subItems
{
NSMutableArray *items = [[NSMutableArray alloc] init];
for (int ar = 0; ar < arrayListstatus.count; ar++)
{
NSArray *thirdarray=[arrayListstatus objectAtIndex:ar] ;
NSLog(#"thirdarray %#",third array);
[items addObject:thirdarray];
}
NSLog(#"itemss %#",items);
return items;
}

i think this should do the trick:
- (NSArray *)subItems
{
NSMutableArray *items = [[NSMutableArray alloc] init];
for (int ar = 0; ar < arrayListstatus.count; ar++)
{
NSArray *thirdarray= [arrayListstatus objectAtIndex:ar] ;
NSMutableDictionary *tmpDict = [NSMutableDictionary alloc] init];
[tmpDict setObject:[thirdarray objectAtIndex:2] forKey:#"Application_ID"];
[tmpDict setObject:[thirdarray objectAtIndex:3] forKey:#"Application_Status"];
[items addObject:tmpDict];
[items addObject:tmpDict];
}
NSSortDescriptor *sortDescriptor;
sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:"Application_Status" ascending:YES], nil]];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [items sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"itemss %#",items);
return items;
}

Related

Sort NSmuatbleArray

I need to sort array (in IOS) like this...
let us suppose that i have an NSMutableArray with : 1,2,3,4,5
i need to build a new array with the last object in the middle and the middle will replace the last : 1.2.5.4.3...
please help:
this is what i doing for now, i got only the 1.2.5 but i not success to put the 4.3 ...
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#1,#2,#3,#4,#5, nil];
int arrCount = (int)arr.count/2;
NSMutableArray *arr2 = [[NSMutableArray alloc] init];
for (int i = 0;i < arr.count; i++) {
if (i < arrCount) {
[arr2 addObject:arr[i]];
}
else{
index = i;
[arr2 addObject:arr.lastObject];
}
}
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#1,#2,#3,#4,#5, nil];
NSMutableArray *arr2 = [[NSMutableArray alloc] initWithArray:arr];
int middleIndex = (int)arr.count/2;
id middleObject = arr2[middleIndex];
[arr2 replaceObjectAtIndex:middleIndex withObject:arr2.lastObject];
[arr2 replaceObjectAtIndex:arr2.count-1 withObject:middleObject];
NSLog(#"%#", arr2);

Sort array in ascending order and remove duplicate values in objective- c

I have a horizontally and vertically scrollable table. I get the data for the header and first column from the web service(json). I want to sort the data in ascending order and remove duplicate data from both header and the first column. For removing duplicate values I used the following code:
-(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];
// NSSet *set = [NSSet setWithArray:left];
// NSArray *array2 = [set allObjects];
// NSLog(#"%#", array2);
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];
}
How will I sort the arrays in ascending order?
Please help.
OK, so you have a model object that looks something like this...
#interface Model: NSObject
#property NSNumber *idNumber;
#property NSNumber *year;
#property NSString *value;
#end
Note, I am intentionally using NSNumber and not NSInteger for reasons that will become clear.
At the moment you are trying to do a lot all in one place. Don't do this.
Create a new object to store this data. You can then add methods to get the data you need. Seeing as you are displaying in a table view sectioned by year and then each section ordered by idNumber then I'd do something like this...
#interface ObjectStore: NSObject
- (void)addModelObject:(Model *)model;
// standard table information
- (NSInteger)numberOfYears;
- (NSInteger)numberOfIdsForSection:(NSinteger)section;
// convenience methods
- (NSNumber *)yearForSection:(NSInteger)section;
- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row;
- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row;
// now you need a way to add objects
- (void)addModelObject:(Model *)model;
#end
Now to implement it.
We are going to store everything in one dictionary. The keys will be years and the objects will be dictionaries. In these dictionaries the keys will be idNumbers and the objects will be arrays. These array will hold the models.
So like this...
{
2010 : {
1 : [a, b, c],
3 : [c, d, e]
},
2013 : {
1 : [g, h, u],
2 : [e, j, s]
}
}
We'll do this with all the convenience methods also.
#interface ObjectStore: NSObject
#property NSMutableDictionary *objectDictionary;
#end
#implementation ObjectStore
+ (instancetype)init
{
self = [super init];
if (self) {
self.objectDictionary = [NSMutableDictionary dictionary];
}
return self;
}
+ (NSInteger)numberOfYears
{
return self.objectDictionary.count;
}
+ (NSInteger)numberOfIdsForSection:(NSinteger)section
{
// we need to get the year for this section in order of the years.
// lets create a method to do that for us.
NSNumber *year = [self yearForSection:section];
NSDictionary *idsForYear = self.objectDictionary[year];
return idsForYear.count;
}
- (NSNumber *)yearForSection:(NSInteger)section
{
// get all the years and sort them in order
NSArray *years = [[self.obejctDictionary allKeys] sortedArrayUsingSelector:#selector(compare:)];
// return the correct year
return years[section];
}
- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row
{
// same as the year function but for id
NSNumber *year = [self yearForSection:section];
NSArray *idNumbers = [[self.objectDictionary allKeys]sortedArrayUsingSelector:#selector(compare:)];
return idNumbers[row];
}
- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row
{
NSNumber *year = [self yearForSection:section];
NSNumber *idNumber = [self idForSection:section row:row];
return self.objectDictionary[year][idNumber];
}
// now we need a way to add objects that will put them into the correct place.
- (void)addModelObject:(Model *)model
{
NSNumber *modelYear = model.year;
NSNumber *modelId = model.idNumber;
// get the correct storage location out of the object dictionary
NSMutableDictionary *idDictionary = [self.objectDictionary[modelYear] mutableCopy];
// there is a better way to do this but can't think atm
if (!idDictionary) {
idDictionary = [NSMutableDictionary dictionary];
}
NSMutableArray *modelArray = [idDictionary[modelId] mutableCopy];
if (!modelArray) {
modelArray = [NSMutableArray array];
}
// insert the model in the correct place.
[modelArray addObject:model];
idDictionary[modelId] = modelArray;
self.objectDictionary[modelYear] = idDictionary;
}
#end
With all this set up you can now replace your complex function with this...
-(void) requestFinished: (ASIHTTPRequest *) request
{
NSString *theJSON = [request responseString];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *jsonDictionary = [parser objectWithString:theJSON error:nil];
for (NSDictionary *dictionary in jsonDictionary)
{
Model *model = [[Model alloc]init];
model.cid = [dictionary valueForKey:#"cid"];
model.idNumber = [dictionary valueForKey:#"iid"];
model.year = [dictionary valueForKey:#"yr"];
model.val = [dictionary valueForKey:#"val"];
[self.objectStore addModelObject:model];
}
}
To get the models out for a particular row then just use...
[self.objectStore modelsForSection:indexPath.section row:indexPath.row];
To get the number of sections in the tableview delegate method...
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [self.objectStore numberOfYears];
}
No messing around with the model in the view controller.
Welcome to the MVC pattern.
There's a crap ton of code here but by placing all the code here you can remove all the complex code from your VC.
NSSet keeps only non-duplicate objects within themselves so to keep only unique objects in array you can use NSSet as -
Suppose you have array with duplicate objects
NSArray *arrayA = #[#"a", #"b", #"a", #"c", #"a"];
NSLog(#"arrayA is: %#", arrayA);
//create a set with the objects from above array as
//the set will not contain the duplicate objects from above array
NSSet *set = [NSSet setWithArray: arrayA];
// create another array from the objects of the set
NSArray *arrayB = [set allObjects];
NSLog(#"arrayB is: %#", set);
The output from the above looks like:
arrayA is: (
a,
b,
a,
c,
a
)
arrayB is: {(
b,
c,
a
)}
and to sort a mutable array in ascending order you can use NSSortDescriptor and sortUsingDescriptors:sortDescriptors. Also you need to provide the key on the basis of which array will be sorted.
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"key" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];
Here you will get what you want.
//sort description will used to sort array.
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:#"iid" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[arrLeft sortedArrayUsingDescriptors:descriptors];
reverseOrder is your desire output.
there is another way you can sort objects that followed model.
NSArray *someArray = /* however you get an array */
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
NSNumber *rank1 = [obj1 valueForKeyPath:#"iid"];
NSNumber *rank2 = [obj2 valueForKeyPath:#"iid"];
return (NSComparisonResult)[rank1 compare:rank2];
}];
here sortedArray is our output.
you can replace same things for yr key as well.
This is what I did to sort the header data in ascending order and to remove duplicates from both header and leftmost column. Hope this will help others
NSOrderedSet *orderedSet3 = [NSOrderedSet orderedSetWithArray:head3];
headData3 = [[orderedSet3 array] mutableCopy];
[headData3 sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2)
{
return [str1 compare:str2 options:(NSNumericSearch)];
}];
NSOrderedSet *orderedSet4 = [NSOrderedSet orderedSetWithArray:left3];
NSMutableArray *arrLeft3 = [[orderedSet4 array] mutableCopy];
[leftTableData3 addObject:arrLeft3];

Compare Values of Database and Json and display result

I am creating a table with multiple columns. In the left column I want to get the indicator name which is stored in a database and I have to check that the indicator id in database and in json (API) matches and then display the name in that column. I have tried some code
In view load method I take values from database and store it in an array
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
appDelegate = (AppDelegate *) [[UIApplication sharedApplication] delegate];
indicatorName = [[NSMutableArray alloc] init];
NSString *path = appDelegate.databasePath;
FMDatabase *db = [[FMDatabase alloc] initWithPath:path];
[db open];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM Topic AS t INNER JOIN TopicIndicators AS ti ON t.Id = ti.TopicId INNER JOIN Indicators AS i ON ti.IndicatorID = i.Id"];// WHERE t.Id = %ld", (long)self.Tid];
FMResultSet *fresult = [db executeQuery:sql];
while ([fresult next])
{
TopicModel *topicModel = [[TopicModel alloc]init];
topicModel.TId = [fresult intForColumn:#"Id"];
topicModel.TTopicType = [fresult stringForColumn:#"TopicType"];
topicModel.TCode = [fresult stringForColumn:#"Code"];
topicModel.TName = [fresult stringForColumn:#"Name"];
topicModel.IId = [fresult intForColumn:#"Id"];
topicModel.ICodeId = [fresult stringForColumn:#"CodeId"];
topicModel.IName = [fresult stringForColumn:#"Name"];
topicModel.INotes = [fresult stringForColumn:#"Notes"];
topicModel.TIId = [fresult intForColumn:#"Id"];
topicModel.TITopicId = [fresult intForColumn:#"TopicId"];
topicModel.TIIndicatorID = [fresult intForColumn:#"IndicatorId"];
[indicatorName addObject:topicModel];
}
[db close];
mainTableData = [[NSMutableArray alloc] init];
[self callPages];
self.title = NSLocalizedString(#"Compare By", nil);
XCMultiTableView *tableView = [[XCMultiTableView alloc] initWithFrame:CGRectInset(self.view.bounds, 5.0f, 5.0f)];
tableView.leftHeaderEnable = YES;
tableView.datasource = self;
[self.view addSubview:tableView];
}
In request finished method I am taking values from json and assigning the values in appropriate columns.
-(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"];
[head addObject:[NSString stringWithFormat:#"%ld", model.yr]];
[left addObject:[NSString stringWithFormat:#"%ld", model.iid]];
[mainTableData addObject:model];
}
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];
NSMutableArray *newArray = [[NSMutableArray alloc] init];
TopicModel *topicModel = [[TopicModel alloc]init];
for (int k = 0; k < arrLeft.count; k++)
{
if (topicModel.IId == arrLeft[k])
{
[newArray addObject:[NSString stringWithFormat:#"%#",topicModel.IName]];
}
}
if([filteredArray count]>0)
{
Model *model = [filteredArray objectAtIndex:0];
[array addObject:model.val];
}
}
[right addObject:array];
}
[rightTableData addObject:right];
}
I am using FMDB, ASIHTTPRequest, SBJSON, XCMultisortTableView.
Please do help.
Well you are creating new TopicModel object which is empty! You need to use the one which you set in your viewDidLoad: method.
for (int k = 0; k < arrLeft.count; k++) {
if ([(TopicModel *)indicatorName[k] IId] == [arrLeft[k] integerValue]) {
[newArray addObject:[NSString stringWithFormat:#"%#",[(TopicModel *)indicatorName[k] IName]];
}
}

How to create a NSDictionnary from an array with custom cells

I have a UITableView with custom cellView populated with an array (cf. functs) without section. My goal is to create a search bar (which is ok) with a list index (which is the problem).
After reading a lot of documentations, I plan to use these three methods: "numberOfSectionsInTableView", "sectionIndexTitlesForTableView" and "sectionForSectionIndexTitle"
How to create the NSDictionnary of functs array with the following structure?
//in viewDidLoad
// Initialize the functs array
Funct *funct1 = [Funct new];
funct1.name = #"AAA";
funct1.detail = #"detail1...";
funct1.image = #"a.jpg";
Funct *funct2 = [Funct new];
funct2.name = #"BBB";
funct2.prepTime = #"detail2...";
funct2.image = #"b.jpg";
functs = [NSArray arrayWithObjects:funct, funct2, nil]; //etc.
//For Index list: one section per letter
NSString *letters = #"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";
self.indexTitlesArray = [letters componentsSeparatedByString:#" "];
Thanks in advance
Here you have a good tutorial with example project. It´s what you are looking for.
It´s an example for TableView indexed, but it has a good example for sections and rows
There is in this example this method very useful for you
static NSString *letters = #"abcdefghijklmnopqrstuvwxyz";
// This method returns an array of dictionaries where each key is a letter
// and each value is a group of words corresponding to the letter.
+ (NSArray *) wordsFromLetters {
NSMutableArray *content = [NSMutableArray new];
for (int i = 0; i < [letters length]; i++ ) {
NSMutableDictionary *row = [[[NSMutableDictionary alloc] init] autorelease];
char currentWord[WORD_LENGTH + 1];
NSMutableArray *words = [[[NSMutableArray alloc] init] autorelease];
for (int j = 0; j < WORD_LENGTH; j++ ) {
if (j == 0) {
currentWord[j] = toupper([letters characterAtIndex:i]);
}
else {
currentWord[j] = [letters characterAtIndex:i];
}
currentWord[j+1] = '\0';
[words addObject:[NSString stringWithCString:currentWord encoding:NSASCIIStringEncoding]];
}
char currentLetter[2] = { toupper([letters characterAtIndex:i]), '\0'};
[row setValue:[NSString stringWithCString:currentLetter encoding:NSASCIIStringEncoding]
forKey:#"headerTitle"];
[row setValue:words forKey:#"rowValues"];
[content addObject:row];
}
return content;
}
You can take the main idea from this resource, but if you prefer, I adapted the code. I think works fine
NSMutableArray *funcsArray = [NSMutableArray array];//Here you add all your functs objects
[funcsArray addObjects: funct1, funct2...];
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"name"
ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray;
sortedArray = [funcsArray sortedArrayUsingDescriptors:sortDescriptors];
NSMutableArray *funcsArrayOrdered = [NSMutableArray array];//Here you add all your functs objects
NSMutableArray *funcsIndexed = [NSMutableArray array];
NSMutableArray *letters = [NSMutableArray array];
NSString *currentLetter = nil;
int numItems = [funcsArrayOrdered count];
for (Funct *functObj in funcsArrayOrdered) {
NSLog(#"funct: %#", functObj.name);
numItems--;
NSString *string = userT.name;
if (string.length > 0) {
NSString *letter = [[string substringToIndex:1] uppercaseString];
if ([currentLetter length] == 0) {
currentLetter = letter;
}
if (![letter isEqualToString:currentLetter] || numItems == 0) {
if ([letter isEqualToString:currentLetter] && numItems == 0) {
[letters addObject:functObj];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
letters = [NSMutableArray array];
}else{
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
letters = [NSMutableArray array];
[letters addObject:functObj];
currentLetter = letter;
if (numItems == 0 && [funcsArrayOrdered count] > 1) {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setValue:currentLetter forKey:#"headerTitle"];
[dic setValue:letters forKey:#"rowValues"];
[funcsIndexed addObject:dic];
}
}
}else {
[letters addObject:functObj];
}
}
}
Now you will have your array of Dictionaries ordered in funcsIndexed

Sorting NSArray of dictionaries by value of a key in the dictionaries

I have an array populated by dictionaries, and I need to sort the array alphabetically by the values of one of the keys of the dictionaries.
This is my array:
tu dictus: (
{
brand = Ryul;
productTitle = Any;
quantity = 1;
subBrand = "Ryul INJ";
type = Product;
},
{
brand = Trol;
productTitle = Different;
quantity = 2;
subBrand = "";
type = Brand;
},
{
brand = Dtor;
productTitle = Any;
quantity = 1;
subBrand = "";
type = Product;
},
{
brand = Ryul;
productTitle = Different;
quantity = 2;
subBrand = "Ryul CHES";
type = SubBrand;
},
{
brand = Anan;
productTitle = Any;
quantity = 1;
subBrand = "";
type = Product;
}
)
Normally for sorting an array I will use
myArray = [uniqueProdsArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
But how do sort using the brand key of the dictionary?
I think this will do it:
brandDescriptor = [[NSSortDescriptor alloc] initWithKey:#"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Coding comes into play, in that sortedArrayUsingDescriptors: will send a valueForKey: to each element in myArray, and then use standard comparators to sort the returned values.
We Got The Solution By Using The Method Follows
[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
Where:-
jsonData - MutableArray Which holds the Parsed JSON Data.
fullname - the data we want to sort.
id - An unique data which comes with the inner dictionary.
As an addition to QED's code,
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:#"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:#[brandDescriptor]];
This clarifies the classes of the variables and optimises the array creation with fast-enumeration.
Thanks
arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([[obj1 valueForKey:#"iUserId"] integerValue] > [[obj2 valueForKey:#"iUserId"] integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([[obj1 valueForKey:#"iUserId"] integerValue] < [[obj2 valueForKey:#"iUserId"] integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
In switf:
var descriptor: NSSortDescriptor = NSSortDescriptor(key: "brand", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])
Use following code for sort using the "brand" key from the dictionary..
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:#"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"sortedArray %#",sortedArray);
Use following code, If you to sorting according two keys from the dictionary; Like, "brand" key and productTitle key from the dictionary:-
NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:#"brand" ascending:YES];
NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:#"productTitle" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
NSArray * sortedArray = [feedData sortedArrayUsingDescriptors:sortDescriptors];
NSLog(#"sortedArray %#",sortedArray);
My code was crashing when using NSSortDescriptor so ended up using a block which works great in my use case, where I am expecting the "rank" to be an NSNumber. If the object can't be converted to an integer it will not sort but it also won't cause a crash.
NSArray *sortedArray = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
long data1 = [[obj1 valueForKey:#"rank"] integerValue];
long data2 = [[obj2 valueForKey:#"rank"] integerValue];
if (data1 > data2) {
return (NSComparisonResult)NSOrderedDescending;
}
if (data1 < data2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSSortDescriptor *brandDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"Position" ascending:YES selector:#selector(localizedStandardCompare:)] autorelease];
NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray *sortedArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors];
array_PreLagData=(NSMutableArray*)sortedArray;
unsorted array
Printing description of arrTemp:
<__NSArrayM 0x10282100>(
{
Milker2 = "11:03:17 AM";
Position = 2;
},
{
Milker1 = "11:03:28 AM";
Position = 25;
},
{
Milker3 = "11:03:18 AM";
Position = 3;
},
{
Milker1 = "11:03:16 AM";
Position = 1;
Strip = "11:32:32 AM";
},
{
Milker1 = "11:03:21 AM";
Position = 10;
}
)
Sorted array
<__NSArrayI 0x101363c0>(
{
Milker1 = "11:03:16 AM";
Position = 1;
Strip = "11:32:32 AM";
},
{
Milker2 = "11:03:17 AM";
Position = 2;
},
{
Milker3 = "11:03:18 AM";
Position = 3;
},
{
Milker1 = "11:03:21 AM";
Position = 10;
},
{
Milker1 = "11:03:28 AM";
Position = 25;
}
)
[enter link description here][1]
[1]: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE
you can do this .
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"d LLLL yyyy"];
NSComparator compareDates = ^(id string1, id string2)
{
NSDate *date1 = [formatter dateFromString:string1];
NSDate *date2 = [formatter dateFromString:string2];
return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:#"date" ascending:NO comparator:compareDates];
[array sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];
Just try it out easiest way...
myArray = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
[tempArray addObjectsFromArray: myArray];
NSString *key = #"brand";
NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
[brandDescriptor release];
[tempArray removeAllObjects];
tempArray = (NSMutableArray*)sortedArray;
[myArray removeAllObjects];
[myArray addObjectsFromArray:tempArray];
Use this for swift 4
let sortedArray = arrayTobeSort.sorted {$0["keyName"].compare($1["keyName"]) == ComparisonResult.orderedAscending}
You can also use ComparisonResult.orderedDescending to sort in descending order

Resources