I have a UISwitch on my UITableViewCell (Custom cell) that is activating switches on other cells without any touch, I don't really know why (I don't have any code activating switches on my cells).
(source: abril.com)
.
(source: abril.com)
.
Code:
//Creating cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
CustomClassCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[CustomClassCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
}
NSDictionary *classDetail = [self.classesArray objectAtIndex:indexPath.row];
cell.textLabel.text = [classDetail objectForKey:#"nome"];
NSString *detailText = [NSString stringWithFormat:#"Professor %# às %#. %# minutos",[classDetail objectForKey:#"professor"], [classDetail objectForKey:#"hora"], [classDetail objectForKey:#"duracao"] ];
NSString *weekDayString = [[self.viewData objectForKey:#"#attributes"] objectForKey:#"index"];
cell.weekDay = [weekDayString integerValue];
cell.detailTextLabel.text = detailText;
cell.cellData = classDetail;
return cell;
}
//CustomClassCell.m
//This action is linked via storyboard to Value Changed on my UISwitch:
-(IBAction)isOn:(id)sender{
UISwitch *switcher = sender;
BOOL isOn = [switcher isOn];
(isOn == YES ? [self activeNotification] : [self deactiveNotification]);
}
-(void)activeNotification{
NSString *classTimeString = [self.cellData objectForKey:#"hora"];
NSArray *hourAndMinutes = [classTimeString componentsSeparatedByString:#":"];
int hour = [[hourAndMinutes objectAtIndex:0] intValue];
int minutes = [[hourAndMinutes objectAtIndex:1] intValue];
UILocalNotification *locNot = [[UILocalNotification alloc] init];
NSDate *now = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit) fromDate: now];
now = [gregorian dateFromComponents:components];
NSDate *alarmDate = [self getDayFromNumber:self.weekDay fromToday:now];
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*minutes];
if (([now compare:alarmDate] == NSOrderedAscending) || ([now compare:alarmDate] == NSOrderedSame) ){
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*(minutes - 30)];
} else {
alarmDate = [alarmDate dateByAddingTimeInterval:60*60*hour + 60*(minutes - 30) + 60*60*24*7];
}
locNot.fireDate = alarmDate;
[[UIApplication sharedApplication] scheduleLocalNotification: locNot];
}
-(void)deactiveNotification{
//TODO: implement deactivation
}
-(NSDate *)getDayFromNumber:(NSInteger)number fromToday:(NSDate *)today{
number++;
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:today];
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - number)];
NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract
toDate:today options:0];
NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit |
NSDayCalendarUnit) fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents:components];
return beginningOfWeek;
}
Any ideas?
Regards!
This is a cell reuse problem because you are reusing cells but you aren't configuring the switch status (which should be done when you configure the cell text).
This requires that you update your source data (classDetail / cellData) as the switches change so that you can use that information later when returning cells. This is both to prevent duplication of changes and the ensure that a selected switch doesn't change to a deselected switch after a cell is scroll off-screen.
Related
Im trying to load an events(data) (from json file) that matches today's date into my tableView when the today's button is pressed then only the data with today's date will be loaded there and when the future button is pressed the events with later dates will be loaded, the only problem I have here is when i run my program nothing is actually happening when I press in either of these UIbuttons, I got all the events regardless their date and without even clicking on any UIButton, u can see below some of my code, it would be great if someone could figure out what is the problem there and since Im not quiet sure about how to use predicate to filter the data:
#property (strong, nonatomic) NSArray *dateEvents;
#end
#implementation HomeViewController {
NSArray *_events;
NSArray *_dateEvents;
}
- (IBAction)upcomingEvents:(id)sender {
NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"dd-MM-YYYY"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(#"mama");
_dateEvents = [_events filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(Events * event, NSDictionary *bindings){
return [event.date isEqualToString:dateString];
}]];
self.myTableView.dataSource = self;
[self.myTableView reloadData];
NSLog(#"yes");
}
Thanks,
I'm not sure this will definitely help, because I can't see enough code so be certain that this is your problem, but you might find it useful to convert all the dates to NSDate objects (so that you can be certain that the problem is NOT that the strings are actually not equal), and then check whether the day is the current day, or not, by using this category method on NSDate:
NSDate+Extensions.m:
static NSCalendar* ___calendar;
#implementation NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date
{
NSCalendar* calendar = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents* comp1 = [calendar components:unitFlags fromDate:date];
NSDateComponents* comp2 = [calendar components:unitFlags fromDate:self];
return [comp1 day] == [comp2 day] &&
[comp1 month] == [comp2 month] &&
[comp1 year] == [comp2 year];
}
-(NSCalendar*)currentCalendar
{
if(___calendar == nil)
{
___calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
}
return ___calendar;
}
#end
NSDate+Extensions.h
#interface NSDate (Extensions)
- (BOOL)isSameDay:(NSDate*)date;
#end
I have a Button in my view.On tapping the Button you get a datepicker which defaults to today's date, the user can then select the date they want to search for events.
The problem is, no matter what date I select, it always returns the current day and adds this to my TextField which i have placed inside mu Button.Can any one tell me where I am wrong.am setting the date picker programatically.
Below is my code hopefully someone can help me out!
//displaying date picker while clicking on button
- (IBAction)startDateButtonAction:(id)sender
{
if ([popOverController isPopoverVisible]) {
[popOverController dismissPopoverAnimated:YES];
}
UIViewController* popoverContent = [[UIViewController alloc] init]; //ViewController
UIView *popoverView1 = [[UIView alloc] init]; //view
datePicker =[[UIDatePicker alloc]init];//Date picker
datePicker.frame =CGRectMake(0,0,240, 150);
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker setMaximumDate:[[NSDate date] dateByAddingTimeInterval:24*60*60*-6]];
[datePicker setMinimumDate:[DateFormatter getSubtractedDateForomCurrentDateWith:35]];
datePicker.date = [DateFormatter getDateFromString:startDateLabel.text];
datePicker.selected = YES;
[datePicker addTarget:self action:#selector(datePickerValue) forControlEvents:UIControlEventValueChanged];
[popoverView1 addSubview:datePicker];
popoverContent.view = popoverView1;
popOverController = [[UIPopoverController alloc] initWithContentViewController:popoverContent];
[popOverController setPopoverContentSize:CGSizeMake(240, 150) animated:NO];
[popOverController presentPopoverFromRect:startDateButton.frame inView:headerView permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}
//action function while selecting any of the date from date picker
- (void) datePickerValue
{
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setDay:-6];
NSDate *labelStartDate = datePicker.date;
startDate = [DateFormatter getOnlyDateComponentsFromDate:labelStartDate];
NSDate *labelEndDate = [self addDayToDate:startDate Number:6];
startDateLabel.text = [DateFormatter getDateStringddmmyyy:labelStartDate];
endDateLabel.text = [DateFormatter getDateStringddmmyyy:labelEndDate];
}
[including the functions that am used here]
//used for getting date components
+(NSDate *) getOnlyDateComponentsFromDate:(NSDate *)date
{
unsigned int flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* components = [calendar components:flags fromDate:date];
NSDate* dateOnly = [calendar dateFromComponents:components];
return dateOnly;
}
- (NSDate *) addDayToDate:(NSDate *)date Number:(int) number
{
NSDate *newDate = [date dateByAddingTimeInterval:60*60*24*number];
return newDate;
}
Iam using ARC.
here datePicker.date gives me only the current date even though I select any other dates
I found out my mistake at last..The problem was with my code where i set the maximum and minimum value for the datePicker.removing the code for setting maximum and minimum value the code works fine..
You need to initialise your datepicker like this.
_datePicker = [[UIDatePicker alloc] initWithFrame:pickerFrame];
_datePicker.tag=1951;
_datePicker.datePickerMode=UIDatePickerModeDate;
[_datePicker addTarget:self action:#selector(ageChanged:) forControlEvents:UIControlEventValueChanged];
[_actionSheet addSubview:_datePicker];
And for your this method: ageChanged:
-(void)ageChanged:(id)sender {
NSDate *datePicked = [_datePicker date];
NSLog(#"%#", datePicked);
formattedDate = [dateFormatter stringFromDate:datePicked];
}
and set dateFormatter as per your requirement.
while changing your date it will give you the date you have selected in date Picker.
I hope this will help you for date picker.
I have this problem. I have a operation. But if i want to save?
I want to save all (textfield data picker and result in a label)
I have 2 textfield and 1 datapicker + the result in a Label.
this is my M :
#import "ViewController.h"
#import "ResultViewController.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize myLabel;
-(IBAction)calculate:(id)sender{
NSDate *past = _data.date ;
NSDate *now = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:past
toDate:now
options:0];
int z = [components day];
int a = ([_textField1.text intValue]);
int b = a*([_textField2.text intValue]);
int r = b * z / 20;
myLabel.text = [[NSString alloc] initWithFormat:#"%d", r];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSDate *past = _data.date ;
NSDate *now = [NSDate date];
NSCalendar *gregorianCalendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger unitFlags = NSDayCalendarUnit;
NSDateComponents *components = [gregorianCalendar components:unitFlags
fromDate:past
toDate:now
options:0];
int z = [components day];
int a = ([_textField1.text intValue]);
int b = a*([_textField2.text intValue]);
int r = b * z / 20;
myLabel.text = [[NSString alloc] initWithFormat:#"%d", r];
self.textField1.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key1"];
self.textField2.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key2"];
self.myLabel.text = [[NSUserDefaults standardUserDefaults] objectForKey:#"key3"];
self.data = [[NSUserDefaults standardUserDefaults] objectForKey:#"key4"];
[[NSUserDefaults standardUserDefaults]synchronize];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"detail"]) {
ResultViewController* destVC = (ResultViewController*)segue.destinationViewController;
destVC.myString = self.myLabel.text;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:YES];
[[NSUserDefaults standardUserDefaults] setObject:self.textField1.text forKey:#"key1"];
[[NSUserDefaults standardUserDefaults] setObject:self.textField2.text forKey:#"key2"];
[[NSUserDefaults standardUserDefaults] setObject:self.myLabel.text forKey:#"key3"];
[[NSUserDefaults standardUserDefaults] setObject:self.data forKey:#"key4"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
#end
This code is Right?
Thank you....
Couple things.
In your -viewDidLoad, you call -synchronize for some reason. All this does is perform the save function for any events on your user defaults. From what I can see, you don't have any and can skip this call to -synchronize.
One of your logs is showing the value of 'r'. The value is an int value and you should use '%i' to display this correctly. You are performing some calculations to get that value, so you may want that to be a double or something else, but you are currently casting it to an int.
I don't see anything regarding the user defaults that looks out of sorts. So maybe you can specify what exactly is wrong or isn't being done correctly to get some better help.
Yes code looks right.
What is your _data variable type?
If you having trouble saving to NSUser. Try to save self.data.date
One tip : You don't need to synchronize after getting values from NSUserdefautls. Use synchronize after setting values to NSUserdefaults.
I am making a reminder app, where user create some event with date and time and choose when he should get noticed about it by choosing a fire date (interval before this event: right now, 5, 15, 30 minutes ago, and so on) and repeat interval (never, daily, weekly, monthly and every year). The problem is: when user creates an event, that already happens, for example event should occur in 10 april, and today is 16 april, he should be reminded about this event right in time, but user gets notification about this event right after creating it. So it shouldn't happened. How can I avoid this?
Here is the method, that creates notification
- (void)notificationWithNote:(Note *)scheduledNote deleteThisNotification:(BOOL)deleteNotification {
NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];
unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit;
NSDateComponents *comp = [calendar components:unitFlags fromDate:scheduledNote.date];
ToDoItem *todoitem = [[ToDoItem alloc] init];
todoitem.day = [comp day];
todoitem.month = [comp month];
todoitem.year = [comp year];
todoitem.hour = [comp hour];
todoitem.minute = [comp minute];
todoitem.eventName = scheduledNote.event;
NSDateComponents *dateComps = [[NSDateComponents alloc] init];
[dateComps setDay:todoitem.day];
[dateComps setMonth:todoitem.month];
[dateComps setYear:todoitem.year];
[dateComps setHour:todoitem.hour];
[dateComps setMinute:todoitem.minute];
NSDate *itemDate = [calendar dateFromComponents:dateComps];
[dateComps release];
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
if (localNotif == nil)
return;
if ([scheduledNote.remindTime intValue] == 1)
localNotif.fireDate = itemDate;
else
localNotif.fireDate = [itemDate dateByAddingTimeInterval:-([scheduledNote.remindTime intValue]*60)];
switch ([scheduledNote.repeatOption intValue]) {
case 0:
localNotif.repeatInterval = 0;
break;
case 1:
localNotif.repeatInterval = NSDayCalendarUnit;
break;
case 2:
localNotif.repeatInterval = NSWeekCalendarUnit;
break;
case 3:
localNotif.repeatInterval = NSMonthCalendarUnit;
break;
case 4:
localNotif.repeatInterval = NSYearCalendarUnit;
break;
default:
break;
}
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:NSLocalizedString(#"%# begins", nil), scheduledNote.event];
localNotif.alertAction = NSLocalizedString(#"View Details", nil);
localNotif.soundName = UILocalNotificationDefaultSoundName;
localNotif.applicationIconBadgeNumber = 1;
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:todoitem.eventName,ToDoItemKey, #"Timenote is coming", MessageTitleKey, nil];
localNotif.userInfo = infoDict;
if (deleteNotification)
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
else
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(#"fire date: %#",[localNotif.fireDate description]);
[todoitem release];
[localNotif release];
}
This bug happens only if user doesn't choose any repeat interval. If event repeats every day/week/month/year, remind appears right in time. So the problem is actual if localNotif.repeatInterval == 0
Looks like, I've found the answer. If issue happens only, when there is no repeat interval, then it needs to check this condition: if fireDate is less then current date and if there is no repeat interval, than this notification shouldn't be scheduled.
NSComparisonResult result = [localNotif.fireDate compare:[NSDate date]];
if (((localNotif.repeatInterval == 0) && (result == NSOrderedAscending)) || deleteNotification)
{
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
}
else
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
How to compare time in Objective C?
if (nowTime > 9:00 PM) && (nowTime < 7:00 AM)
{
doSomething;
}
If you want to get the current hour and compare it to some times, you're going to have to use NSDate, NSDateComponents, and NSCalendar.
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currentHour = [components hour];
NSInteger currentMinute = [components minute];
NSInteger currentSecond = [components second];
if (currentHour < 7 || (currentHour > 21 || currentHour == 21 && (currentMinute > 0 || currentSecond > 0))) {
// Do Something
}
That will check if the time is between 9:00 PM and 7:00 AM. Of course, if you're going to want different times you'll have to change the code a little.
Read about NSDate, NSDateComponents, and NSCalendar to learn more.
Theres a perfect formula for this. Just for future references
Below is the sample code :
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
NSString *startTime = #"21:00";
NSString *endTime = #"07: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 = (int)((currHr*60)+currtMin);
if(nowTime >= formStTime && nowTime <= formEnTime) {
// Do Some Nasty Stuff..
}
NSDate *now = [NSDate date];
if (([now compare:earlierDateVariable] == NSOrderedDescending) && ([now compare:laterDateVariable] == NSOrderedAscending ))
{
// Do something here...
}
To set earlierDate and laterDate, straight from Apple's documentation available here
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:22];
[comps setMonth:03];
[comps setYear:2011];
[comps setHour:21];
[comps setMinute:00];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *earlierDateVariable = [gregorian dateFromComponents:comps];
[comps release];
[gregorian release];
And the same goes for later date...
For checking current time or any time between two times ::
NSCalendar *calendar = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
return [self isDateComponent:components withinStartHour:startH startMin:startM endHour:endH endMin:endM];
-(BOOL)isDateComponent:(NSDateComponents*)components withinStartHour:(int)startH startMin:(int)startM endHour:(int)endH endMin:(int)endM
{
if (endH < startH) {
return ( [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:23 endMin:59] ||
[self isDateComponent:components betweenStartHour:0 startmin:0 endHour:endH endMin:endM] );
}
else {
return [self isDateComponent:components betweenStartHour:startH startmin:startM endHour:endH endMin:endM];
}
}
-(BOOL)isDateComponent:(NSDateComponents*)components betweenStartHour:(int)startH startmin:(int)startM endHour:(int)endH endMin:(int)endM
{
int currentH = components.hour;
int currentM = components.minute ;
DDLogVerbose(#"start : %i-%i, end : %i-%i, current:%i-%i",startH,startM,endH,endM,currentH,currentM);
startM = startM + startH * 60;
endM = endM + endH * 60;
currentM = components.minute + currentH*60;
if ( startM <= currentM && currentM < endM ) {
return YES;
}
else {
return NO;
}
}
I used the Answer Given above by rye. I just had to convert my 7:00 AM and 9:00 PM to 24 hours. Here's the method I used
/**
Willl return YES if the Restaurant is OPEN at the Moment else NO
*/
-(BOOL) isShopOpen:(NSString *) startTime closeTime:(NSString *) endTime{
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit fromDate:[NSDate date]];
NSInteger currHr = [components hour];
NSInteger currtMin = [components minute];
int stHr ;
int stMin ;
int enHr ;
int enMin ;
if([startTime containsString:#"PM"]){
startTime = [startTime stringByReplacingOccurrencesOfString:#" PM" withString:#""];
stHr=[[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
stHr=stHr+12;
stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}else{
startTime = [startTime stringByReplacingOccurrencesOfString:#" AM" withString:#""];
stHr=[[[startTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
stMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}
if([endTime containsString:#"PM"]){
endTime = [endTime stringByReplacingOccurrencesOfString:#" PM" withString:#""];
enHr=[[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
enHr=enHr+12;
enMin = [[[startTime componentsSeparatedByString:#":"] objectAtIndex:1] intValue];
}else{
endTime = [endTime stringByReplacingOccurrencesOfString:#" AM" withString:#""];
enHr=[[[endTime componentsSeparatedByString:#":"] objectAtIndex:0] intValue];
enMin = [[[startTime 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 Nasty Stuff..
return YES;
}else{
return NO;
}
}
If anybody needs, this is a code to create sections in a tableView according to the date of objects.
Method to get dates for today, yesterday, etc. (taken from ReMail project DateUtil class):
#define DATE_UTIL_SECS_PER_DAY 86400
-(void)refreshData {
//TODO(gabor): Call this every hour or so to refresh what today, yesterday, etc. mean
NSCalendar *gregorian = [NSCalendar currentCalendar];
self.today = [NSDate date];
self.yesterday = [today dateByAddingTimeInterval:-DATE_UTIL_SECS_PER_DAY];
self.lastWeek = [today dateByAddingTimeInterval:-6*DATE_UTIL_SECS_PER_DAY];
self.todayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:today];
self.yesterdayComponents = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit) fromDate:yesterday];
self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
}
Method to sort tableData for table view sections according to date:
// Sort tableData objects according to the date
for (MCMessage *mcMessage in self.tableData) {
NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:mcMessage.dateTime];
NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];
NSLog(#"Day:%d, Month:%d, Year:%d. Today day:%d. Yesterday:%d", day, month, year, dateUtil.todayComponents.day, dateUtil.yesterdayComponents.day);
if ((dateUtil.todayComponents.day == day) && (dateUtil.todayComponents.month == month) && (dateUtil.todayComponents.year == year))
{
[self.todayData addObject:mcMessage];
}
else if ((dateUtil.yesterdayComponents.day == day) && (dateUtil.yesterdayComponents.month == month) && (dateUtil.yesterdayComponents.year == year))
{
[self.yesterdayData addObject:mcMessage];
}
else
{
[self.soonerData addObject:mcMessage];
}
}