这个应用程序应该记录自生日(1996年)以来的秒数,但是当我尝试记录NSLog(@"It has been %f seconds since the start of 1996.", seconds);
时它会记录:
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
我的问题是为什么打印(null)?这是Xcode中的Objective-C命令行工具应用程序。任何建议将不胜感激!感谢
我正在使用的代码:
// main.m
// TimeAfterTime
//
// Created by JP on 1/28/14.
// Copyright (c) 2014 Big Nerd Ranch. All rights reserved.
//
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1996];
[comps setMonth:11];
[comps setDay:7];
[comps setHour:13];
[comps setMinute:23];
[comps setSecond:0];
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *dateOfBirth = [g dateFromComponents:comps];
NSDate *now = [[NSDate alloc] init];
NSLog(@"This NSDate object lives at %p", now);
NSLog(@"The date is %@", now);
double seconds = [now timeIntervalSinceDate:dateOfBirth];
NSLog(@"It has been %f seconds since the start of 1996.", seconds);
}
return 0;
}
在控制台中打印的结果:
2014-01-29 11:36:15.752 TimeAfterTime[750:303] This NSDate object lives at 0x100103680
2014-01-29 11:36:15.756 TimeAfterTime[750:303] The date is 2014-01-29 16:36:15 +0000
2014-01-29 11:36:15.756 TimeAfterTime[750:303] It has been (null) seconds since the start of 1996.
Program ended with exit code: 0
答案 0 :(得分:3)
NSCalendar *g = [[[NSCalendar alloc] init] initWithCalendarIdentifier:NSGregorianCalendar];
应该是
NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
由于初始化错误,g = nil
因此dateOfBirth = nil
。