最新消息:20210917 已从crifan.com换到crifan.org

【已解决】iOS中,从NSDateFormatter的stringFromDate中获得的值,始终是空字符串/nil

iOS crifan 2914浏览 0评论

【问题】

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

代码如下:

-(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。

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

- (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中,另外还初始化了:

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

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

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

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

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

 

【总结】

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

以后要记住这些教训。

转载请注明:在路上 » 【已解决】iOS中,从NSDateFormatter的stringFromDate中获得的值,始终是空字符串/nil

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

网友最新评论 (1)

    96 queries in 0.181 seconds, using 23.36MB memory