在iOS程序中,调用NSDateFormatter的stringFromDate,传入的参数也是正确的NSDate*,但是结果得到的值,始终是空值/nil。

代码如下:

?

1
2
3
4
-(IBAction)dateChangedAction:(id)sender{
     NSDate* selectedDate = self.datePicker.date;
     self.dateInput.text = [self.dateFormatter stringFromDate:selectedDate];
}

【解决过程】

1.对于程序的代码,反复确认了,保证对于stringFromDate的使用上,没有什么问题。

2.网上搜索相关内容,找到了:

stringFromDate always NIL

Objective -C Date Formatter Examples – stringFromDate

然后才注意到,原来人家使用stringFromDate之前,都是有对应的NSDateFormatter的alloc和init的。

而自己这里好像没有。。。

所以就去添加进去。

3.而添加的位置,要找个合适的位置才好。

然后就去参考了之前就参考的代码DateCell,看到了人家是在viewDidLoad就去添加了相关代码的初始化的,包括上述的dateFormatter。

然后自己也就去对应的位置,添加了相关初始化代码:

?

1
2
3
4
5
6
7
8
9
10
11
- ( void )viewDidLoad
{
     [super viewDidLoad];
     
     birdNameList = [[NSArray alloc] initWithObjects:@ "Ostrich" , @ "Penguin" , @ "HummingBird" , @ "Peacock" , @ "Sparrow" , nil];
     
     self.birdNamePickerView.delegate = self;
     [self.birdNamePickerView selectRow:1 inComponent:0 animated:YES];
     [self.birdNamePickerView reloadAllComponents];
     self.dateFormatter = [[NSDateFormatter alloc] init];
}

然后运行了下,结果竟然还是空的字符串,而不是所期望的格式化的日期字符串。

4.然后再继续调试,最后发现,原来人家DateCell中,另外还初始化了:

?

1
2
[self.dateFormatter setDateStyle:NSDateFormatterShortStyle];
[self.dateFormatter setTimeStyle:NSDateFormatterNoStyle];

这样后期所用到的dateFormatter才能正常使用的。

所以就又去添加了同样的代码,变为:

?

1
2
3
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateStyle:NSDateFormatterShortStyle];
[self.dateFormatter setTimeStyle:NSDateFormatterNoStyle];

然后再去测试,最后终于可以正常工作了,从NSDateFormatter的stringFromDate中所获得值,就是所期望的日期了:

 

【总结】

对于任何变量,都需要有初始化,并且很多对象类型的变量,需要做一些初始值的设定,然后一些基本的函数,才可以使用的。

以后要记住这些教训。