How to compare curent time lie between two time slot - iphone

I hava an array of NSDictionary like this.
{
id = 12;
"time_from" = "12:00";
"time_to" = "16:00";
"timing_name" = Lunch;
},
{
id = 11;
"time_from" = "08:00";
"time_to" = "12:00";
"timing_name" = BreakFast;
},
{
id = 13;
"time_from" = "09:00";
"time_to" = "10:00";
"timing_name" = Dinner;
}
Suppose my current time is 8:45 then how can we find exact dictionary using predicate if current time exit between time_from and time_to.
Actully i need a predicate.

You can try this,
NSMutableArray *testArray = [NSMutableArray array];
NSMutableDictionary *testDict = [NSMutableDictionary dictionary];
[testDict setObject:#"12:45" forKey:#"time-from"];
[testDict setObject:#"14:45" forKey:#"time-to"];
[testArray addObject:testDict];
NSPredicate *timePredicate = [NSPredicate predicateWithBlock:^BOOL(NSMutableDictionary *dict, NSDictionary *bindings) {
NSString *timeFromString = [dict objectForKey:#"time-from"];
NSString *timeToString = [dict objectForKey:#"time-from"];
// find minutes from 00-0
//get current time minutes from 00-00
return (currentTimeMinutes>startimeMinutes) && (currentTimeMinutes<=endtimeMinutes)
}];
[testArray filterUsingPredicate:timePredicate];

-(void)makeCalculation
{
NSMutableDictionary *temp=[[NSMutableDictionary alloc]init];
[temp setObject:#"13" forKey:#"id"];
[temp setObject:#"12:00" forKey:#"timeFrom"];
[temp setObject:#"16:00" forKey:#"timeTo"];
NSMutableDictionary *temp1=[[NSMutableDictionary alloc]init];
[temp1 setObject:#"13" forKey:#"id"];
[temp1 setObject:#"08:00" forKey:#"timeFrom"];
[temp1 setObject:#"12:00" forKey:#"timeTo"];
NSMutableDictionary *temp2=[[NSMutableDictionary alloc]init];
[temp2 setObject:#"13" forKey:#"id"];
[temp2 setObject:#"09:00" forKey:#"timeFrom"];
[temp2 setObject:#"10:00" forKey:#"timeTo"];
NSMutableArray *arrayOfDict=[[NSMutableArray alloc]init];
[arrayOfDict addObject:temp];
[arrayOfDict addObject:temp1];
[arrayOfDict addObject:temp2];
NSMutableArray *timeToCompare=[[NSMutableArray alloc]initWithObjects:#"8:45",#"8:45", nil];
for(int k=0;k<[arrayOfDict count];k++)
{
NSMutableDictionary *temp=[arrayOfDict objectAtIndex:k];
NSString *timeFrom=[temp objectForKey:#"timeFrom"];
NSString *timeTo=[temp objectForKey:#"timeTo"];
NSMutableArray *tempTocheck=[[NSMutableArray alloc]initWithObjects:timeFrom,timeTo, nil];
if([self isTimeClash:timeToCompare compareWith:tempTocheck])
{
NSLog(#"Time Belong in id:%#",[temp objectForKey:#"id"]);
}
}
}
-(BOOL)isTimeClash:(NSMutableArray *)timeToCheck compareWith:(NSMutableArray *)timeToCompare
{
int Start1=[self getMinitesFromTime:[timeToCheck objectAtIndex:0]];
int end1=[self getMinitesFromTime:[timeToCheck objectAtIndex:1]];
int start2=[self getMinitesFromTime:[timeToCompare objectAtIndex:0]];
int end2=[self getMinitesFromTime:[timeToCompare objectAtIndex:1]];
if(start2>=end1 || end2<=Start1)
{
NSLog(#"Clash not happeed");
return NO;
}
else
{
NSLog(#"clash hapens ");
return YES;
}
}
-(int)getMinitesFromTime:(NSString *)timeINHours
{
NSInteger hrVal1 = [(timeINHours) intValue] ;
NSArray *array1 = [timeINHours componentsSeparatedByString:#":"];
int minVal1 = [[array1 lastObject]intValue];
hrVal1 = hrVal1 *60;
minVal1 = hrVal1 + minVal1;
return minVal1;
}

Try to use this one...
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString *startTime = #"10:00";
NSString *endTime = #"16:00";
int stHr = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int enHr = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
int enMin = [[[endTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
int formStTime = (stHr*60)+stMin;
int formEnTime = (enHr*60)+enMin;
int nowTime = (currHr*60)+currtMin;
if(nowTime >= formStTime && nowTime <= formEnTime)
{
// Do Some Stuff..
}

The array timings contains you array. You may want to include the time in 24 hour format for uniformity.
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"HH:mm"];
NSDate *now = [NSDate date];
__block NSString *status = nil;
[timings enumerateObjectsUsingBlock:^(NSDictionary * dict, NSUInteger idx, BOOL *stop)
{
NSDate *date1 = [dateFormatter dateFromString:dict[#"time_from"]];
NSDate *date2 = [dateFormatter dateFromString:dict[#"time_to"]];
NSDateComponents *date1Components = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:date1];
NSDateComponents *date2Components = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:date2];
NSDateComponents *nowDateComponents = [[NSCalendar currentCalendar]components:NSHourCalendarUnit|NSMinuteCalendarUnit
fromDate:now];
NSInteger fromMinutes = date1Components.hour*60+date1Components.minute;
NSInteger toMinutes = date2Components.hour*60+date2Components.minute;
NSInteger nowMinutes = nowDateComponents.hour*60+nowDateComponents.minute;
if (nowMinutes>fromMinutes && nowMinutes<toMinutes) {
status = dict[#"timing_name"];
}
}];
NSLog(#"%#",status);

Related

Information not being received from server?

Okay, my problem is very simple. Below is my code that is receiving prices from an API, in my code I want the today current price to be displayed, yesterdays price, and the change in percent from yesterday to today. Unfortunately, only the current price is showing properly, but the yesterday and the percent change just show N/A.
Any help is appreciated!
if (refreshing) return;
refreshing = YES;
UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
//self.priceLabel.text = #"Loading...";
//self.yesterdayLabel.text = #"Loading...";
//self.changeLabel.text = #"Loading...";
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:#"https://coinbase.com/api/v1/prices/spot_rate"]] queue:[NSOperationQueue mainQueue] completionHandler:^ (NSURLResponse *req, NSData *recv, NSError *err) {
if (err) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSError *newError = nil;
NSDictionary *serial = [NSJSONSerialization JSONObjectWithData:recv options:0 error:&newError];
if (newError) {
// report
[self setCurrentPrice:#"N/A"];
refreshing = NO;
return;
}
NSString *amount = [serial objectForKey:#"amount"];
NSString *price = [NSString stringWithFormat:#"%# %#", amount, [serial objectForKey:#"currency"]];
[self setCurrentPrice:[NSString stringWithFormat:#"%#", price]];
// maybe setup a better method.
float diff = [yesterdaysPrice floatValue];
if (diff == 0.0)
self.differenceInPrices = #"N/A";
else {
float amt = [amount floatValue];
float percentChange = amt/diff;
if ((diff == 0) || (amt == diff))
percentChange = 0.00;
percentChange *= 100.00;
self.differenceInPrices = [NSString stringWithFormat:#"%f%%", percentChange];
}
NSMutableDictionary *saveState = [[[NSUserDefaults standardUserDefaults] objectForKey:#"save"] mutableCopy];
[saveState setObject:price forKey:#"price"];
[saveState setObject:yesterdaysPrice forKey:#"lastCheckedPrice"];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
[saveState setObject:[NSString stringWithFormat:#"%ld", (usingYesterdaysPrices ? [[saveState objectForKey:#"day"] intValue] : [compon day])] forKey:#"day"];
[[NSUserDefaults standardUserDefaults] setObject:saveState forKey:#"save"];
[[NSUserDefaults standardUserDefaults] synchronize];
self.priceLabel.text =self.currentPrice;
self.yesterdayLabel.text = [NSString stringWithFormat:#"%#", yesterdaysPrice];
self.changeLabel.text = differenceInPrices;
app.networkActivityIndicatorVisible = NO;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"MM/dd/yyyy"];
NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
[timeFormat setDateFormat:#"h:mm:ss aa"];
NSDate *now = [[NSDate alloc] init];
NSString *theDate = [dateFormat stringFromDate:now];
NSString *theTime = [timeFormat stringFromDate:now];
lstUpdate.text = [NSString stringWithFormat:#"Updated: %# at %#", theDate, theTime];
refreshing = NO;
}];
I also have this code in my viewDidLoad,
[super viewDidLoad];
refreshing = NO;
NSDictionary *save = [[NSUserDefaults standardUserDefaults] objectForKey:#"save"];
if (save) {
int timeStamp = [[save objectForKey:#"day"] intValue];
NSDateComponents *compon = [[NSCalendar currentCalendar] components:(NSUndefinedDateComponent) fromDate:[NSDate date]];
if ([compon day] != timeStamp) {
usingYesterdaysPrices = YES;
yesterdaysPrice = [save objectForKey:#"lastCheckedPrice"];
if (!yesterdaysPrice) {
yesterdaysPrice = #"N/A";
}
}
}
else {
yesterdaysPrice = #"N/A";
}
self.differenceInPrices = #"N/A";
[self sendNewRequest:nil];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(sendNewRequest:) userInfo:Nil repeats:YES];

Manage Multiple UILocal Notification

I have created multiple UI local Notifications , say 100. I have an array of UILocalNotifications which are scheduled as:
-(void) scheduleNotification{
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
[self.notifications removeAllObjects];
for (int i = 0; i< [delegate.viewController.contactList count] ; i++) {
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
NSString *name = [[delegate.viewController.contactList objectAtIndex:i]objectForKey:NAME_KEY];
NSString *birthday = [[delegate.viewController.contactList objectAtIndex:i]objectForKey:BIRTHDAY_KEY];
if (birthday) {
[formatter setDateFormat:#"MM/dd/yyyy"];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
NSDate *date = [formatter dateFromString:birthday];
if (date == nil) {
[formatter setDateFormat:#"MM/dd"];
[formatter setLocale:[NSLocale currentLocale]];
[formatter setTimeZone:[NSTimeZone systemTimeZone]];
date = [formatter dateFromString:birthday];
}
NSCalendar *gregorianEnd = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *componentsEnd = [gregorianEnd components:NSWeekdayCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
componentsEnd.year = [[NSDate date] year];
date = [gregorianEnd dateFromComponents:componentsEnd];
self.alarmTime = [date dateByAddingTimeInterval:self.mTimeInterval];
localNotification.fireDate = _alarmTime;
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.applicationIconBadgeNumber = 1;
NSString *itemName = #"B'day Alert!!!";
NSString *msgName = [NSString stringWithFormat:#"Celebrate %#'s B'day",name];
NSDictionary *userDict = [NSDictionary dictionaryWithObjectsAndKeys:itemName,MessageKey, msgName,TitleKey, nil];
localNotification.userInfo = userDict;
localNotification.soundName = self.soundName;
localNotification.alertBody = [NSString stringWithFormat:#"Celebrate %#'s B'day",name];
[self.notifications addObject:localNotification];
}
}
}
}
I have implemented my applicationDidEnterBackground delegate as:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
UILocalNotification* notification;
for (int i = 0; i< [self.settingVC.notifications count]; i++) {
notification = [self.settingVC.notifications objectAtIndex:i];
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
}
Also, in didReceiveLocalNotification delegate I have this:
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification
{
NSString *itemName = [notification.userInfo objectForKey:TitleKey];
NSString *messageTitle = [notification.userInfo objectForKey:MessageKey];
[self _showAlert:itemName withTitle:messageTitle];
application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}
But the problem is that i'm not getting desired output.Any help would be appreciated. I know that at an application can have only a limited number of scheduled notifications; the system keeps the soonest-firing 64 notifications and discards the rest. So, how I will handle those 100 or more UILocalNotification?

Loading dates from core data

I have a view with lots of labels, each one corresponding to a week day and a type of task. I want to load information from core data and use that information to set each label's text.
#import "WeekViewController.h"
#implementation WeekViewController
- (void) viewDidLoad {
gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
[gregorian setFirstWeekday:2];
mondayMeetings = 0;
mondayPhoneCalls = 0;
mondayToDos = 0;
tuesdayMeetings = 0;
tuesdayPhoneCalls = 0;
tuesdayToDos = 0;
wednesdayMeetings = 0;
wednesdayPhoneCalls = 0;
wednesdayToDos = 0;
thursdayMeetings = 0;
thursdayPhoneCalls = 0;
thursdayToDos = 0;
fridayMeetings = 0;
fridayPhoneCalls = 0;
fridayToDos = 0;
saturdayMeetings = 0;
saturdayPhoneCalls = 0;
saturdayToDos = 0;
sundayMeetings = 0;
sundayPhoneCalls = 0;
sundayToDos = 0;
[self loadInfo:[NSDate date]];
}
- (void) loadInfo:(NSDate *)date {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(Date >= %#) AND (Date <= %#)", [self dateByMovingToBeginningOfWeek:self.selectedDate], [self dateByMovingToEndOfWeek:self.selectedDate]];
request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Task" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
[request setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"Date" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error = nil;
mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
}
for (int i = 0; i < [mutableFetchResults count]; i++) {
Task *aTask = (Task *)[mutableFetchResults objectAtIndex:i];
NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:aTask.Date];
int weekday = [comps weekday];
if (weekday == 1 && [aTask.Type isEqualToString:#"PhoneCall"]) {
mondayPhoneCalls ++;
}
}
NSLog(#"%d", mondayPhoneCalls);
for (UILabel *go in [self.view subviews]) {
if (go.tag == 1) {
go.text = [NSString stringWithFormat:#"%i", mondayPhoneCalls];
}
}
}
- (NSDate *) dateByMovingToEndOfWeek:(NSDate *)date {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *parts = [gregorian components:flags fromDate:date];
[parts setWeekday:7];
[parts setHour:23];
[parts setMinute:59];
[parts setSecond:59];
return [gregorian dateFromComponents:parts];
}
- (NSDate *) dateByMovingToBeginningOfWeek:(NSDate *)date {
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekdayCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *parts = [gregorian components:flags fromDate:date];
[parts setWeekday:0];
[parts setHour:0];
[parts setMinute:0];
[parts setSecond:0];
return [gregorian dateFromComponents:parts];
}
#end
But it only registers a task if it's date is the current date(sunday by the way). Also can anyone think of a more efficient way to set each label's text than either having an outlet for each one, or looping through all of the view's subviews and checking their tags?
Any help much appreciated.
Your predicate is now saying "objects whose date is today's date or later AND whose date is today's date or earlier". The only objects who fulfill that requirement are the ones with today date.
For your other question, you can look at an IBOutletCollection. They are used for collections of similar objects (in your case UILabel). It's basically an NSArray of IB objects, which you can loop over and easily set their values.

how to convert currency in word spell in iphone? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I create the function to convert the Currency to Word Format but my problem is that when put the textfeild value 100000 i need Indian Format one lakh,but it give me one hundred thousand so any solution for that.
NSString *str1 = txtAmount.text;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSString *localeStr = [appDel.countryCodeDict valueForKey:appDel.selectedCountry];
if ([appDel.selectedCountry isEqualToString:#"France"]) {
localeStr = #"fr";
}
if ([appDel.selectedCountry isEqualToString:#"Germany"]) {
localeStr = #"de";
}
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:localeStr];
[formatter setLocale:usLocale];
[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSArray *valueArr=[str1 componentsSeparatedByString:#"."];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSString *firstStr = [valueArr objectAtIndex:0];
NSString *seconfStr = [valueArr lastObject];
if (valueArr.count==2 && ![seconfStr isEqualToString:#""]) {
double firstAmt = [firstStr doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:firstAmt]];
double secondAmt = [seconfStr doubleValue];
NSString *convertStr1 = [formatter stringFromNumber:[NSNumber numberWithDouble:secondAmt]];
NSString *finalStr = [convertStr stringByAppendingFormat:#" %# %# %#",appDel.firstCurrencystr,convertStr1,appDel.secondCurrencystr];
NSLog(#"%#",finalStr);
NSString *firstCapChar = [[finalStr substringToIndex:1] capitalizedString];
tempStr = [finalStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}else{
double firstAmt = [firstStr doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:firstAmt]];
convertStr = [convertStr stringByAppendingFormat:#" %#",appDel.firstCurrencystr];
NSString *firstCapChar = [[convertStr substringToIndex:1] capitalizedString];
tempStr = [convertStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}
appDel.lblAmountView.lblAmount.text = tempStr;
Any idea of that.
Dont' know what you have coded but if you want currency to be in indian style check out this code:-
NSLocale *indiaLocale = [[[NSLocale alloc] initWithLocaleIdentifier:#"en_IN"] autorelease];
double currency = 1000000000.00;
NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
[numberFormatter setNumberStyle: NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:indiaLocale];
NSString *numberAsString = [numberFormatter stringFromNumber:[NSNumber numberWithInt:currency]];
NSString *str2 = [NSString stringWithFormat:#"Converted:%#",numberAsString];
NSLog(#"String:%#",str2);
at last i convert the hole currency in lakh and crore format of india:
-(NSString *)stringfromNumberIndia:(NSString *)str_word
{
NSString *tempStr=#"";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:#"en_IN"];
[formatter setLocale:usLocale];
[formatter setNumberStyle: NSNumberFormatterSpellOutStyle];
if ([str_word length]>5) {
NSString* str_convert = [str_word substringFromIndex:[str_word length]-5];
NSString* str_convert1 = [str_word substringToIndex:[str_word length]-5];
NSLog(#"str :%#",str_convert);
NSLog(#"str1 :%#",str_convert1);
tempStr = [[self stringfromNumberIndia:str_convert] stringByAppendingString:tempStr];
int l=[str_convert1 length];
for (int i=0; i<l;) {
NSRange range;
if (l>2 && i == 0) {
range=NSMakeRange(l-i-2, 2);
}
else{
range=NSMakeRange(0, l-i);
}
NSString *str_first=[str_convert1 substringWithRange:range];
if ([str_first intValue] == 0) {
if (i == 0)
i+=2;
else
break;
continue;
}
NSLog(#"str_first:%#",str_first);
if (i== 0) {
str_first=[formatter stringFromNumber:[NSNumber numberWithDouble:[str_first doubleValue]]];
str_first = [str_first stringByAppendingFormat:#" lakh "];
tempStr = [str_first stringByAppendingString:tempStr];
}
else {
str_first =[self stringfromNumberIndia:str_first];
str_first = [str_first stringByAppendingFormat:#" crore "];
tempStr = [str_first stringByAppendingString:tempStr];
break;
}
i+=2;
}
}
else if ([str_word intValue] !=0){
double Amt = [str_word doubleValue];
NSString *convertStr = [formatter stringFromNumber:[NSNumber numberWithDouble:Amt]];
NSString *firstCapChar = [convertStr substringToIndex:1];
tempStr = [convertStr stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
}
return tempStr;
}
Thanks.

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

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.)