ios - dateFormat 错误返回 nil

标签 ios objective-c swift uitableview nsdate

作为练习 Objective-C 的练习,我正在将 Swift 代码转换为 Objective-C。在转换了 1.5k 行之后,我发现自己在过去几天在最后一期上被封锁了。

在我的 TableViewController 的几个单元格中,描述标签根本没有出现。我检查了我的代码,似乎传递给单元格的字符串实际上是空的或 nil。

在将返回日期的 Swift 代码转换到我的单元格时,我似乎犯了语法错误。我犯了什么错误导致日期为零?

代码:

ViewController.m

...

NSDate const *now = [[NSDate alloc] init];
NSDate *date = [[NSDate alloc] init];

self.sections =  [[NSMutableArray<NSString *> alloc]init];
self.items = [[NSMutableArray<NSMutableArray<TableItem *> *> alloc]init];
self.sectionItems = [[NSMutableArray<TableItem *> alloc]init];

...

这是未正确加载的单元格数据(空字符串传递给 theDescription):

anItem = [[TableItem alloc ]initWithTitle: @"Custom: dd MMM yyyy HH:mm:ss" theDescription: [NSString stringWithFormat:@"%@", [now toString: [DateFormat CustomDateFormat:@"dd MMM yyyy HH:mm:ss"]]]];
        [_sectionItems addObject: anItem];

//theDescription should be: @"25 April 2016 15:04:57" after this ^, but is actually nil or @""

anItem = [[TableItem alloc ]initWithTitle: @"ISO8601(Year)" theDescription: [NSString stringWithFormat:@"%@", [now toString: [DateFormat ISODateFormat: ISOFormatYear]]]];
        [_sectionItems addObject: anItem];

//theDescription should be: @"2016" after this ^, but is actually nil or @""

这是我认为我犯了错误的地方:

原始的 Swift 语法:

扩展.swift

toString() 函数

 case .ISO8601(let isoFormat):
        dateFormat = (isoFormat != nil) ? isoFormat!.rawValue : ISO8601Format.DateTimeMilliSec.rawValue
        zone = NSTimeZone.localTimeZone()

我尝试过的:

扩展.m

else if([format.dateFormatType compare: ISO8601DateFormatType] == NSOrderedSame) {
    NSString *isoFormat = ISO8601DateFormatType;
    dateFormat =  (isoFormat != nil) ? isoFormat : ISOFormatDateTimeMilliSec;
    zone = [NSTimeZone localTimeZone];
}

最佳答案

问题出在这一行:

NSDateFormatter *formatter = [NSDate formatter : dateFormat : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];

dateFormat@"Custom",因为它在此处设置:

else if([format.dateFormatType compare: CustomDateFormatType] == NSOrderedSame) {
    NSString *string = CustomDateFormatType;
    dateFormat = string;
}

这将传递到您的 NSDateFormatter 构造函数中:

formatter.dateFormat = format;

@"Custom" 不是有效的日期格式字符串。相反,传入 format.formatDetails:

NSDateFormatter *formatter = [NSDate formatter : format.formatDetails : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];

我应该注意到,在 Objective-C 中不使用命名参数会使您的代码更难阅读。

关于ios - dateFormat 错误返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36753954/

相关文章:

ios - Swift 没有激活标签的风格替代品

objective-c - 核心数据 : Observing changes in related entities

ios - iOS 应用程序是否可以直接以纸板模式播放 youtube 视频?

swift - 如何从 cellForRowAtIndexPath 更改行高?

ios - 5分钟后如何在后台调用api?

javascript - 在 iOS 中是否存在用于退出 "select scroller"接口(interface)的 vendor 特定事件?

ios - 容器 View 不检查滚动中的 UITableView 数据?

ios - Firebase 推送通知 swift 3

iOS 13 UITableViewCell自定义accessoryView出界

ios - 自动布局动态 UITableView 单元格高度