日期格式错误 returns 无

Error in dateFormat returns nil

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

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

我似乎在将 returns 日期的 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语法:

Extension.swift

toString() 函数

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

我尝试了什么:

Extension.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 中不使用命名参数会使您的代码更难阅读。