[英]NSDate keeps returning nil
当用户单击按钮时,它将获得今天的日期/时间。 开始日期和结束日期返回nil
我有这些实例变量:
@property (strong) NSDate *startingDate;
@property (strong) NSDate *endingDate;
@property (strong) NSDateFormatter *dateFormatter;
在我的初始化方法中:
startingDate = [NSDate date];
endingDate = [startingDate dateByAddingTimeInterval:600];
现在我的更新方法:
-(void)updateCountdown {
dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"mm:ss"]; //format date for minutes and seconds
NSCalendar *calendar = [NSCalendar currentCalendar];
NSUInteger unitFlags = NSMinuteCalendarUnit|NSSecondCalendarUnit;
NSDateComponents *dateComponants = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];
NSInteger minutes = [dateComponants minute];
NSInteger seconds = [dateComponants second];
NSString *countdownText = [NSString stringWithFormat:@" %d Minute %d Seconds", minutes, seconds];
timeLabel.text = countdownText;
NSLog (@"Startdate is %@ and Enddate is %@.", startingDate, endingDate);
NSLog(countdownText);
[self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];
}
我现在的问题是startDate和endDate都返回nil?
编辑:感谢所有回答的人,我的init完好无损,
我必须添加:
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
startingDate = [NSDate date];
endingDate = [startingDate dateByAddingTimeInterval:600];
}
我的猜测是您没有使用initWithCoder
方法进行初始化,而是调用initWithFrame
方法。
- (id)initWithCoder:(NSCoder *)aDecoder
是您使用的语言,使用xib或情节提要时会被调用。
方法 :
- (id)initWithFrame:(CGRect )frame
当您以编程方式初始化视图时,就是所谓的。 尝试实现init代码是一个单独的方法,并从initWithCoder和initWithFrame中进行调用。 这样,您将从两种调用中获得相同的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.