I have a Dictionary of format [Int:Any] I have bunch of key value pairs in it. I want to sort out the dictionary using the millisecond time format
[169887: ["noti_type": 0, "project_name": "Design Project", "eventCount": 6, "author_pic": " /file/download/profile$2348d4f21095a01cc16a8ad9bf08f966.jpg", "canvas_name": "Design Reference #31 : Windows in NYC", "lastUpdatedAt": 1513585053629, "author_name": "Jake Kyung "],
173865: ["noti_type": 0, "project_name": "BeeCanvas DEV", "eventCount": 13, "author_pic": " &&&& /file/download/profile$80bbc9731a859d4e083df0df8044bcde.jpg &&&& /file/download/profile$2348d4f21095a01cc16a8ad9bf08f966.jpg", "canvas_name": "Android Release note", "lastUpdatedAt": 1513307315308, "author_name": " &&&& Sukho Bu &&&& Jake Kyung "]
I have a bunch of these kind of values in my Dictionary. I want to sort them using the lastUpdatedAt value which is 1513585053629 millisecond format.
I have gone through some posts which said this is possible if I can use a NSDate,
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: #"dateOfInfo" ascending: NO];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
[sortDescriptor release];
But I was just wondering if I could achieve this directly using the millisecond format instead of converting to NSDate ?
This is just demo for understanding..
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]init];
[dict1 setObject:#"Design Project" forKey:#"project_name"];
[dict1 setObject:#"1513585053629" forKey:#"lastUpdatedAt"];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
[dict2 setObject:#"BeeCanvas DEV" forKey:#"project_name"];
[dict2 setObject:#"1513307315308" forKey:#"lastUpdatedAt"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:dict1];
[arr addObject:dict2];
NSLog(#"original array = %#",arr);
you can give directly key name in sort descriptor.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey: #"lastUpdatedAt" ascending:YES];
NSArray *sortedArray = [arr sortedArrayUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
NSLog(#"sorted array = %#",sortedArray);
Output:-
sorted array = (
{
lastUpdatedAt = 1513307315308;
"project_name" = "BeeCanvas DEV";
},
{
lastUpdatedAt = 1513585053629;
"project_name" = "Design Project";
}
)
Related
I have a mutable array containing some arrays for use in a table view controller. The arrays contain a title and some other information. I want the arrays in the master array to be sorted alphabetically in terms of the title they contain. I have assigned the titles with keys:
NSString *title = #"objectTitle";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_storedTitle.text, title, nil];
NSArray *newArray = #[#"Login", dict, _storedUsername.text, _storedPassword.text];
I store the newArray in my masterArray and try to sort the array thus:
//sort array alphabetically
NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:#"objectTitle" ascending:YES];
NSArray *sortDescriptors = #[titleDescriptor];
NSArray *sortedArray = [_masterArray sortedArrayUsingDescriptors:sortDescriptors];
_masterArray = sortedArray.copy;
This is not working, as i have not specified the index where the titleDescriptor is stored. How do I do this?
When accessing the title at a given index (index) in the master array is done as follows:
NSLog(#"%#", [[[_masterArray objectAtIndex:index] objectAtIndex:1] objectForKey:#"objectTitle"]);
Modified your code like this:-
NSSortDescriptor *sortedDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"objecttitle"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:sortedDescriptor, nil];
NSArray * sortedArray =
[array sortedArrayUsingDescriptors:descriptors];
NSlog(#"%#",sortedArray);
I want to sort a mutable array by date. My array contains several dict with keys say:key1,key2,birthday.Now, I have to sort by its birthday key:
I know that this can be done using:
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:#"birthday" ascending:YES];
[myArray sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
But my problem is that I want to sort only those arrays, which don’t contain empty birthday field. My array will contains several empty birthday fields. I don’t want to sort those.
Finally I have to load these in table view through [self.mTable reloadData];.
First collect the indices of all objetcs without a birthday.
NSIndexSet *indexSet = [NSIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL *stop)
{
if(![[dict allKeys] containsObject:#"birthday"]){
[indexSet addIndex:idx];
}
}];
Now remove them from the original array
[array removeObjectsAtIndexes:indexSet];
Using a comparator block, sorting could look like
[array sortUsingComparator: ^(NSDictionary *d1, NSDictionary *d2) {
NSDate *date1 = [d1 objectForKey:#"birthday"];
NSDate *date2 = [d2 objectForKey:#"birthday"];
return [date1 compare:date2]
}
Create a different array to back your table view like this:
NSDictionary* obj1 = [NSDictionary dictionaryWithObject: [NSDate date] forKey: #"birthday"];
NSDictionary* obj2 = [NSDictionary dictionaryWithObject: [NSDate dateWithTimeIntervalSince1970: 0] forKey: #"birthday"];
NSDictionary* obj3 = [NSDictionary dictionaryWithObject: #"wow" forKey: #"no_birthday"];
NSArray* all = [NSArray arrayWithObjects: obj1, obj2, obj3, nil];
NSArray* onlyWithBirthday = [all valueForKeyPath: #"#unionOfObjects.birthday"];
And if you need the full objects for the table view, continue with this code:
NSPredicate* filter = [NSPredicate predicateWithFormat: #"SELF.birthday IN %#", onlyWithBirthday];
NSArray* datasource = [all filteredArrayUsingPredicate: filter];
Then you can apply your sort method of choice.
Here's what I have:
An NSMutableArray that holds several NSDictionary Objects.
Each NSDictionary has a Date String as an Element.
Here's my loop that prints out the Date in each NSDictionary
[dateFormatterIn setDateFormat:#"yyyyMMddHHmmss\n"];
[dateFormatterOut setDateFormat:#"dd.MM.yyyy"];
for(NSMutableDictionary *thisStory in stories){
id fromDate = [thisStory objectForKey:#"from_time"];
id date = [dateFormatterIn dateFromString:fromDate];
NSLog(#"%#", [dateFormatterOut stringFromDate:date]);
}
Does anyone have a clue how I can sort my array stories by date?
I am quite new to objective C.
Thanks in advance!
Using the your stories array's sortUsingDescriptor method should do the trick:
NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey: #"from_time" ascending: YES] autorelease];
[stories sortUsingDescriptors: [NSArray arrayWithObject: sortDescriptor]];
Let's assume Following data structure : array variable name: collectionArray =
[
{
date: "01-02-2015 02:01",
value: 1,
name: "rajan"
},
{
date: "01-02-2014 02:01",
value: 11,
name: "rajan1"
},
{
date: "01-02-2012 02:01",
value: 111,
name: "rajan2"
}
]
Now to sort this array of nsdictionary by date we follow the following steps
`NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"dd-MM-yyyy HH:mm"];
NSMutableArray *sortedArray = [[collectionArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *d1Str =[obj1 valueForKey:#"date"];
NSString *d2Str =[obj2 valueForKey:#"date"]
NSString *d1Timestamp = [NSString stringWithFormat:#"%f", [[formatter dateFromString:d1Str] timeIntervalSince1970]];
NSString *d2Timestamp = [NSString stringWithFormat:#"%f", [[formatter dateFromString:d2Str] timeIntervalSince1970]];
return [d2Timestamp compare:d1Timestamp options:NSNumericSearch]; // descending order
}] mutableCopy];`
I am new in iPhone development. I need your help in sorting NSArray.
in this Code I am assigning values to the MyData. this is a NSArray variable.
NSMutableArray *MyArray=[NSMutableArray array];
[MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:314564454],#"Population", #"Mumbai",#"Name", [NSNumber numberWithInt:415452],#"Area",nil]];
[MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys[NSNumber numberWithInt:454154412],#"Population", #"Chennai",#"Name", [NSNumber numberWithInt:324544],#"Area",nil]];
[MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:874544541],#"Population", #"Kolkatta",#"Name", [NSNumber numberWithInt:554445],#"Area",nil]];
[MyArray addObject:[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:412541245],#"Population", #"Delhi",#"Name", [NSNumber numberWithInt:345475],#"Area",nil]];
self.MyData = [NSArray arrayWithArray:MyArray];
Now I need top 3 Cities with the Highest Population Information.
So I had Write Following Code.,
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:#"Population" ascending:NO] autorelease];
NSArray *sorted = [self.MyData sortedArrayUsingDescriptors:
[NSArray arrayWithObject:sorter]];
NSRange range = NSMakeRange(0,3);
return [sorted subarrayWithRange:range];
But it is not working.
The same code works if I replace the following
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:#"Population" ascending:NO] autorelease];
with
NSSortDescriptor *sorter = [[[NSSortDescriptor alloc] initWithKey:#"Name" ascending:NO] autorelease];
This Works..
Because Name is String.
Please help me out How can I sort this array with numeric value.
Thank you in advance.
A quick run of your code gives to following output which seems right for me:
2010-07-29 16:32:59.774 test[93035:207] (
{
Area = 554445;
Name = Kolkatta;
Population = 874544541;
},
{
Area = 324544;
Name = Chennai;
Population = 454154412;
},
{
Area = 345475;
Name = Delhi;
Population = 412541245;
}
)
I just replaced your return with: NSLog(#"%#", [sorted subarrayWithRange:range]);
Cheers...
I have a array of NSString objects which I have to sort by descending.
Since I did not find any API to sort the array in descending order I approached by following way.
I wrote a category for NSString as listed bellow.
- (NSComparisonResult)CompareDescending:(NSString *)aString
{
NSComparisonResult returnResult = NSOrderedSame;
returnResult = [self compare:aString];
if(NSOrderedAscending == returnResult)
returnResult = NSOrderedDescending;
else if(NSOrderedDescending == returnResult)
returnResult = NSOrderedAscending;
return returnResult;
}
Then I sorted the array using the statement
NSArray *sortedArray = [inFileTypes sortedArrayUsingSelector:#selector(CompareDescending:)];
Is this right solution? is there a better solution?
You can use NSSortDescriptor:
NSSortDescriptor* sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO selector:#selector(localizedCompare:)];
NSArray* sortedArray = [inFileTypes sortedArrayUsingDescriptors:#[sortDescriptor]];
Here we use localizedCompare: to compare the strings, and pass NO to the ascending: option to sort in descending order.
or simplify your solution:
NSArray *temp = [[NSArray alloc] initWithObjects:#"b", #"c", #"5", #"d", #"85", nil];
NSArray *sortedArray = [temp sortedArrayUsingComparator:
^NSComparisonResult(id obj1, id obj2){
//descending order
return [obj2 compare:obj1];
//ascending order
return [obj1 compare:obj2];
}];
NSLog(#"%#", sortedArray);
NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"length" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[wordsArray sortUsingDescriptors:sortDescriptors];
Using this code we can sort the array in descending order on the basis of length.