Objects Sorting With date ,Time Problem in Array(Iphone Development) - iphone

I have Problem related to array Sorting.
I have an NSMutable array say's A.Which has an class object b on its each index.
class b contain's multiple field Like int,string and nsdate.
I want to sort the A array on the basis of class b time(NSdate) ascendingly.
I follow the date sorting question on stackoverflow but that's only for date array.
Sort NSArray of date strings or objects
Kindly guide me.
Thank's in advance

Here you go just modify some part of code for your requirement
- (NSArray *)sortedWeightEntriesByWeightDate:(NSArray *)unsortedArray {
NSMutableArray *tempArray = [NSMutableArray array];
NSMutableArray *sortedArray = [NSMutableArray arrayWithCapacity:0];
#try {
for(int i = 0; i < [unsortedArray count];i++) {
NSDateFormatter *df = [[NSDateFormatter alloc]init];
MyDataModal *entry = [unsortedArray objectAtIndex:i];
[df setDateFormat:#"yyyy-MM-dd"];
NSDate *date = [df dateFromString:entry.weightDate];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
if(date) {
[dict setObject:entry forKey:#"entity"];
[dict setObject:date forKey:#"date"];
[tempArray addObject:dict];
}
[df release];
}
NSInteger counter = [tempArray count];
NSDate *compareDate;
NSInteger index;
for(int i = 0 ; i < counter; i++) {
index = i;
compareDate = [[tempArray objectAtIndex:i] valueForKey:#"date"];
NSDate *compareDateSecond;
for(int j = i+1 ; j < counter; j++) {
compareDateSecond=[[tempArray objectAtIndex:j] valueForKey:#"date"];
NSComparisonResult result = [compareDate compare:compareDateSecond];
if(result == NSOrderedDescending) {
compareDate = compareDateSecond;
index=j;
}
}
if(i!=index)
[tempArray exchangeObjectAtIndex:i withObjectAtIndex:index];
}
NSInteger counterIndex = [tempArray count];
for(int i = 0; i < counterIndex ; i++) {
[sortedArray addObject:[[tempArray objectAtIndex:i] valueForKey:#"entity"]];
}
}
#catch (NSException * e) {
NSLog(#"An exception occured while sorting weight entries by date");
}
#finally {
return [NSArray arrayWithArray:sortedArray];
}
}

How about:
NSArray *myArray = [NSArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantFuture], #"theDate", nil],
[NSDictionary dictionaryWithObjectsAndKeys:[NSDate distantPast], #"theDate", nil],
nil];
NSLog(#"Before sorting: %#", myArray);
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey: #"theDate" ascending: YES];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:[NSArray arrayWithObject: dateSortDescriptor]];
NSLog(#"After Sorting: %#", sortedArray);
This presumes that the date you want to sort for has a key (it is a property, essentially.)

Related

how to combine two mutable arrays values in single mutable array? [duplicate]

This question already has answers here:
How would I combine two arrays in Objective-C?
(2 answers)
Closed 9 years ago.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"json.... %#",json);
id jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#", jsonObject);
NSDictionary *checkArray=[json valueForKey:#"ND"];
NSArray *tel = [checkArray valueForKey:#"FN"];
testArray = [[NSMutableArray alloc]init];
testArray1 = [[NSMutableArray alloc]init];
newsarray = [[NSMutableArray alloc]init];
for (id photo in tel)
{
if (photo == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray addObject:test8];
}
else
{
// photo isn't null. It's an array
NSArray *innerPhotos = photo;
[testArray addObject:photo];
}
}
NSArray *tel1 = [checkArray valueForKey:#"LN"];
for (id photo1 in tel1)
{
if (photo1 == [NSNull null])
{
NSString *test8;
test8 = #"empty";
[testArray1 addObject:test8];
}
else
{
// photo isn't null. It's an array
//NSArray *innerPhotos1 = photo1;
[testArray1 addObject:photo1];
}
}
newsarray = [NSMutableArray arrayWithArray:[testArray arrayByAddingObjectsFromArray:testArray1]];
NSLog(#"testArray =%#",newsarray);
here i want to combine two array values "testArray" and "testArray1"
my mutablearray values are
testArray = aa, bb, cc, dd...
testArray1= xx, yy, zz, ss...
i would like to expect my output like
aa xx, bb yy, cc zz, dd ss
Try this:
for (int i=0;i<[testArray count];i++){
NSString *tmpObject=[NSString stringWithFormat:#"%# %#",
[testArray objectAtIndex:i],
[testArray1 objectAtIndex:i]];
[newArray addObject tmpObject];
tmpObject=nil;
}
you can do something like below..
NSMutableArray *aryFinal=[[NSMutableArray alloc]init];
int count = [testArray count]+[testArray1 count];
for(int i=0;i<count;i++)
{
if(i%2==0)
[aryFinal addobject:[testArray objectAtIndex:i]];
else
[aryFinal addobject:[testArray1 objectAtIndex:i]];
}
let me know it is working or not!!!
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"AA",#"BB",#"CC" nil];
NSArray *array2 = [NSArray arrayWithObjects:#"XX",#"YY",#"ZZ" nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i
withObject:[NSString stringWithFormat:#"%# %#",
array1[i],
array2[i]]];
NSLog(#"%#",array1);
Output:
"AA XX","BB YY","CC ZZ"
To simply add two arrays:
[testArray setArray: testArray1];
But if you want desired result:
NSMutableArray *arrFinal=[[NSMutableArray alloc]init];
for(int i = 0; i < (testArray.count + testArray1.count); i++)
{
if(i%2 == 0)
[arrFinal addobject:[testArray objectAtIndex:i]];
else
[arrFinal addobject:[testArray1 objectAtIndex:i]];
}
Do not need to go for third array. You can use replaceObjectAtIndex method of NSMutableArray.
This way..
NSMutableArray *array1 = [NSMutableArray arrayWithObjects:#"aa",#"bb", nil];
NSArray *array2 = [NSArray arrayWithObjects:#"xx",#"yy", nil];
for (int i=0; i<[array1 count];i++)
[array1 replaceObjectAtIndex:i withObject:[NSString stringWithFormat:#"%# %#",array1[i],array2[i]]];
for aa xx, bb yy, cc zz, dd ss output:
int i=-1;
for(int k =0;k<[testArray1 count];++k)
{
i=i+2;
[testArray insertObject:[testArray1 objectAtIndex:k] atIndex:i];
}
NSMutableArray *array1,*array2;
//////array1 and array2 initialise it with your values
NSMutableArray *finalArray = [[NSMutableArray alloc]init]
int totalcount = 0;
if (array1.count > array2.count) {
totalcount = array1.count;
}
else
totalcount = array2.count;
for (int i = 0; i<totalcount; i++) {
if (i <= array1.count-1) {
[finalArray addObject:[array1 objectAtIndex:i]];
}
if (i <= array2.count-1) {
[finalArray addObject:[array2 objectAtIndex:i]];
}
}

Sum duplicate on NSMutableArray

I have a NSMutableArray with objects of type NSMutableDictionary,
the NSMutableDictionary contains 2 keys
-Airlines (string)
-Rating (integer)
I have an NSMutableArray with all the objects and what i need is to Sum the rating of all the airline companies repeated objects, an example:
Airline Rating
A 2
B 3
B 4
C 5
The end result array will be the A = 2, C = 5 and the Sum of B´s that is equal to 7.
My code so far:
for (int i = 0; i < arrayMealRating.count; ++i) {
NSMutableDictionary *item = [arrayMealRating objectAtIndex:i];
NSLog(#"item=%#",item);
for (int j = i+1; j < arrayMealRating.count; ++j)
{
if ([[item valueForKey:#"Airline"] isEqualToString:[arrayMealRating objectAtIndex:j]]){
NSMutableDictionary *item = [arrayMealRating objectAtIndex:j];
NSMutableDictionary *item1 = [arrayMealRating objectAtIndex:i];
NSInteger auxCount = [[item valueForKey:#"setMealRating"] integerValue] + [[item1 valueForKey:#"setMealRating"] integerValue];
NSMutableDictionary *aux = [NSMutableDictionary dictionaryWithObjectsAndKeys:[item valueForKey:#"Airline"], #"Airline"
,[NSString stringWithFormat:#"%d",auxCount], #"setMealRating"
,nil];
NSLog(#"aux=%#",aux);
[arrayMealRating replaceObjectAtIndex:i withObject:aux];
}
}
}
A bit messy i know but i dont know how to work with NSMutableDictionary, any help will be much appreciated, Thanks in Advance!
Incase you dont want to change how your storing the data, heres how you would do it using key-value coding. Heres the dirrect link to the documentation for #distinctUnionOfObjects and #sum.
// Get all the airline names with no duplicates using the KVC #distinctUnionOfObjects collection operator
NSArray *airlineNames = [arrayMealRating valueForKeyPath:#"#distinctUnionOfObjects.Airline"];
// Loop through all the airlines
for (NSString *airline in airlineNames) {
// Get an array of all the dictionaries for the current airline
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(Airline == %#)", airline];
NSArray *airlineMealRating = [arrayMealRating filteredArrayUsingPredicate:predicate];
// Get the sum of all the ratings using KVC #sum collection operator
NSNumber *rating = [airlineMealRating valueForKeyPath:#"#sum.Rating"];
NSLog(#"%#: %#", airline, rating);
}
This gives the following output
A: 2
B: 7
C: 5
I would suggest to redesign that entirely if that's at all possible.
Create a class Airline
#interface Airline : NSObject
#property (strong, nonatomic) NSString *name;
#property (strong, nonatomic) NSMutableArray *mealRatings;
- (void)addMealRating:(float)rating;
- (float)sumOfMealRatings;
#end
#implementation
- (id)initWithName:(NSString *)pName
{
self = [super init];
if (self)
{
self.name = pName;
self.mealRatings = [NSMutableArray array];
}
return self;
}
- (void)addMealRating:(float)rating
{
[self.mealRatings addObject:#(rating)];
}
- (float)sumOfRatings
{
float sum = 0;
for (NSNumber *rating in self.mealRatings)
{
sum += [rating floatValue];
}
}
#end
Then in your 'mainclass' you simply hold an NSArray with instances of your Airline objects. It might require you to change some of your existing code, but I think in the long run it saves you time and trouble. Perhaps you recognize later on, that you want to add additional properties to your Airlines. A dictionary is a cumbersome way to do that.
#try this
NSMutableArray *myArray = [[NSMutableArray alloc] initWithCapacity:4];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[NSNumber numberWithInteger:2] forKey:#"A"];
[myArray addObject:dict];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc] init];
[dict2 setValue:[NSNumber numberWithInteger:3] forKey:#"B"];
[myArray addObject:dict2];
NSMutableDictionary *dict3 = [[NSMutableDictionary alloc] init];
[dict3 setValue:[NSNumber numberWithInteger:4] forKey:#"B"];
[myArray addObject:dict3];
NSMutableDictionary *dict4 = [[NSMutableDictionary alloc] init];
[dict4 setValue:[NSNumber numberWithInteger:5] forKey:#"D"];
[myArray addObject:dict4];
NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc] init];
for(NSMutableDictionary *dictionary in myArray)
{
NSString *key = [[dictionary allKeys] objectAtIndex:0];
NSInteger previousValue = [[resultDictionary objectForKey:key] integerValue];
NSInteger value = [[dictionary objectForKey:key] integerValue];
previousValue += value;
[resultDictionary setObject:[NSNumber numberWithInteger:previousValue] forKey:key];
}
for(NSString *key in resultDictionary)
{
NSLog(#"value for key = %# = %d",key, [[resultDictionary valueForKey:key] integerValue]);
}

NSMutableDictionary does not sort correctly

Let i have unsorted NSMutableDictionary
{
A = "3";
B = "2";
C = "4";
}
And i need result to be like:
{
B = "2";
A = "3";
C = "4";
}
How can i achieve this result in objective c.
A simple code implementation will be appreciated.
Not possible with an NSMutableDictionary, it is not a sorted structure. You will have to turn it into an NSArray and then sort that. You will then not have a dictionary structure.
You can not sort NSMutableDictionary by value as #joe and #mavrick3 answer. However if you change there keys and values to NSArray you can do it..
Here is simple implementation..
NSMutableDictionary *results; //dictionary to be sorted
NSMutableDictionary *results; //dict to be sorted
NSArray *sortedKeys = [results keysSortedByValueUsingComparator: ^(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue])
return (NSComparisonResult)NSOrderedDescending;
if ([obj1 integerValue] < [obj2 integerValue])
return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}];
NSArray *sortedValues = [[results allValues] sortedArrayUsingSelector:#selector(compare:)];
//Descending order
for (int s = ([sortedValues count]-1); s >= 0; s--) {
NSLog(#" %# = %#",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}
//Ascending order
for (int s = 0; s < [sortedValues count]; s++) {
NSLog(#" %# = %#",[sortedKeys objectAtIndex:s],[sortedValues objectAtIndex:s]);
}
You can try this to sort your Dictionary.
NSMutableDictionary *tmpDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"6",#"A",#"3",#"B",#"5",#"C",#"2",#"D",#"21",#"F",#"20",#"G",nil];
NSArray *sortedArray = [tmpDict keysSortedByValueUsingComparator:^NSComparisonResult(id obj1,id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSLog(#"Sorted = %#",sortedArray);
NSDictionaryas well as NSMutableDictionary cannot be sorted by value. You can only use a NSArray to sort them. But you have to this with your own code and you won't get the same output as you want.
This is the simplest way to do this
NSArray *arr = [NSArray arrayWithObjects:#"2", #"4", #"1", nil];
NSArray *sorted = [arr sortedArrayUsingSelector:#selector(compare:)];
NSLog(#"Pre sort : %#", arr);
NSLog(#"After sort : %#", sorted);
If you have f.ex. array of dictionary (or model objects), you could do this :
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:#"Mannie" forKey:#"name"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:#"Zannie" forKey:#"name"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObject:#"Cannie" forKey:#"name"];
NSArray *peopleIKnow = [NSArray arrayWithObjects:dict1, dict2, dict3, nil];
NSSortDescriptor *sorty = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
NSArray *results = [peopleIKnow sortedArrayUsingDescriptors:[NSArray arrayWithObject:sorty]];
NSLog(#"Before : %#", peopleIKnow);
NSLog(#"After : %#", results);

Crazy array sorting in tableView! sortedArrayUsingSelector help?

My tableView app loads the data into the table view.
Everything works perfectly, but the array sorting is kind of messed, like you can see in the picture below. I thought about using the sortedArrayUsingSelector, to straighten things up, but I'm not sure which "sorting method" I should use.
How can I sort this so the cells are sorted according the numbers? Like the order would be 1. 2. 3. 4. 5. etc NOT 1. 10. 11. 12. 13. 14. 2. 3. ?
Thanks a lot in advance!!
And a two-liner:
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:nil ascending:YES comparator:^(id obj1, id obj2) { return [obj1 compare:obj2 options:NSNumericSearch]; }];
rowTitleArray = [rowTitleArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
Sorry for this convoluted approach, but this does work...
NSArray *rowTitleArray = [[NSArray alloc] initWithObjects:
#"10. Tenth",
#"15. Fifteenth",
#"13. Thirteenth",
#"1. First",
#"2. Second",
#"22. TwentySecond", nil];
NSMutableArray *dictionaryArray = [NSMutableArray array];
for (NSString *original in rowTitleArray) {
NSString *numberString = [[original componentsSeparatedByString:#"."] objectAtIndex:0];
NSNumber *number = [NSNumber numberWithInt:[numberString intValue]];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
number, #"number", original, #"rowTitle", nil];
[dictionaryArray addObject:dict];
}
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:#"number" ascending:YES];
NSArray *sortedDictionaryArray = [dictionaryArray sortedArrayUsingDescriptors:
[NSArray arrayWithObject:descriptor]];
NSMutableArray *sortedRowTitles = [NSMutableArray array];
for (NSDictionary *dict in sortedDictionaryArray) {
[sortedRowTitles addObject:[dict objectForKey:#"rowTitle"]];
}
rowTitleArray = [NSArray arrayWithArray:sortedRowTitles];
NSLog(#"%#", rowTitleArray);
Output:
"1. First",
"2. Second",
"10. Tenth",
"13. Thirteenth",
"15. Fifteenth",
"22. TwentySecond"
I will try to think of a more elegant solution.
Here is a more elegant solution:
NSInteger intSort(id num1, id num2, void *context) {
NSString *n1 = (NSString *) num1;
NSString *n2 = (NSString *) num2;
n1 = [[n1 componentsSeparatedByString:#"."] objectAtIndex:0];
n2 = [[n2 componentsSeparatedByString:#"."] objectAtIndex:0];
if ([n1 intValue] < [n2 intValue]) {
return NSOrderedAscending;
}
else if ([n1 intValue] > [n2 intValue]) {
return NSOrderedDescending;
}
return NSOrderedSame;
}
rowTitleArray = [rowTitleArray sortedArrayUsingFunction:intSort context:NULL];

UISearchBar - search a NSDictionary of Arrays of Objects

I'm trying to insert a search bar in a tableview, that is loaded with information from a NSDictionary of Arrays. Each Array holds and object. Each object has several properties, such as Name or Address.
I've implemented the methods of NSSearchBar, but the code corresponding to the search it self, that i have working on another project where the Arrays have strings only, is not working, and I can't get to thr problem.
Here's the code:
'indiceLateral' is a Array with the alphabet;
'partners' is a NSDictionary;
'RLPartnersClass' is my class of Partners, each one with the properties (name, address, ...).
-(void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];
for (NSString *key in self.indiceLateral) {
NSMutableArray *array = [partners valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array) {
if ([name rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}
if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.indiceLateral removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[theTable reloadData];
}
Can anyone help me please?
Thanks,
Rui Lopes
I've done it.
Example:
-(void)handleSearchForTerm:(NSString *)searchTerm {
NSMutableDictionary *finalDict = [NSMutableDictionary new];
NSString *currentLetter = [[NSString alloc] init];
for (int i=0; i<[indiceLateral count]; i++) {
NSMutableArray *elementsToDict = [[[NSMutableArray alloc] init] autorelease];
currentLetter = [indiceLateral objectAtIndex:i];
NSArray *partnersForKey = [[NSArray alloc] initWithArray:[partnersCopy objectForKey:[indiceLateral objectAtIndex:i]]];
for (int j=0; j<[partnersForKey count]; j++) {
RLNames *partnerInKey = [partnersForKey objectAtIndex:j];
NSRange titleResultsRange = [partnerInKey.clientName rangeOfString:searchTerm options:NSDiacriticInsensitiveSearch | NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0){
NSLog(#"found: %#", partnerInKey.clienteCity
[elementsToDict addObject:partnerInKey];
}
}
[finalDict setValue:elementsToDict forKey:currentLetter];
}
NSMutableDictionary *finalResultDict = [finalDict mutableDeepCopy];
self.partners = finalResultDict;
[finalResultDict release];
[theTable reloadData];
}