我非常喜欢新手和作为我学习目标的一部分 - 我决定想出这个简单的应用程序 - 我希望显示过去和过去之间的时间。当前日期 - 显示的内容不断更新,即秒和&分钟等等。继续计算。
这是我到目前为止所拥有的:
- (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;
}
我遇到两个问题:
答案 0 :(得分:1)
我建议将所有与时间相关的代码移动到一个新方法中,可能称为- (void)showTime
。然后你可以创建一个这样的计时器:
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
将此计时器存储在您班级的实例变量中,这样您就可以在以后不再需要它时使其无效。