Reputation: 1229
I'm very much a newbie & as part of my learning objective-c I decided to come up with this simple app - I want to show the time between a date in the past & the current date - with what is being displayed constantly updating i.e. seconds & minutes etc. keep counting up.
Here's what I have so far:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss '+0000'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormat setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *birthDate = [dateFormat dateFromString:@"Fri, 17 Feb 1989 13:00:00 +0000"];
NSDate *todaysDate = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger timeComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit;
NSDateComponents *comps = [gregorian components:timeComponents fromDate:birthDate toDate:todaysDate options:0];
NSInteger numberOfYears = [comps year];
NSInteger numberOfMonths = [comps month];
NSInteger numberOfDays = [comps day];
NSInteger numberOfHours = [comps hour];
NSInteger numberOfSeconds = [comps second];
NSString *yearsString = [NSString stringWithFormat:@"%ld", (long)numberOfYears];
_years.text = yearsString;
NSString *monthsString = [NSString stringWithFormat:@"%ld", (long)numberOfMonths];
_months.text = monthsString;
NSString *daysString = [NSString stringWithFormat:@"%ld", (long)numberOfDays];
_days.text = daysString;
NSString *hoursString = [NSString stringWithFormat:@"%ld", (long)numberOfHours];
_hours.text = hoursString;
NSString *secondsString = [NSString stringWithFormat:@"%ld", (long)numberOfSeconds];
_seconds.text = secondsString;
}
I'm having two problems:
Upvotes: 0
Views: 133
Reputation: 9093
I recommend moving all of your time-related code into a new method, perhaps called - (void)showTime
. Then you can create a timer like this:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
Store this timer in an instance variable for your class so you can invalidate and nil it later when you don't need it anymore.
Upvotes: 1