问题
As an exercise to practice Objective-C, I am converting Swift code to Objective-C. After 1.5k lines converted, I find myself blocked for the past few days on one last issue.
In a few cells of my TableViewController, the description labels don't appear at all. I checked my code, and it seems the strings that are passed to the cells are actually empty or nil.
I seem to have made a syntax error in converting the Swift code that returns the date to my cells. What error have I made that makes the date nil?
THE CODE:
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];
...
This is the cell data that doesn't load correctly (empty strings are passed to 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 @""
Here's where I think I've made a mistake:
Original Swift syntax:
Extension.swift
toString() function
case .ISO8601(let isoFormat):
dateFormat = (isoFormat != nil) ? isoFormat!.rawValue : ISO8601Format.DateTimeMilliSec.rawValue
zone = NSTimeZone.localTimeZone()
What I tried:
Extension.m
else if([format.dateFormatType compare: ISO8601DateFormatType] == NSOrderedSame) {
NSString *isoFormat = ISO8601DateFormatType;
dateFormat = (isoFormat != nil) ? isoFormat : ISOFormatDateTimeMilliSec;
zone = [NSTimeZone localTimeZone];
}
回答1:
The problem is in this line:
NSDateFormatter *formatter = [NSDate formatter : dateFormat : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];
dateFormat
is @"Custom"
, as it was set here:
else if([format.dateFormatType compare: CustomDateFormatType] == NSOrderedSame) {
NSString *string = CustomDateFormatType;
dateFormat = string;
}
This is passed into your NSDateFormatter
constructor here:
formatter.dateFormat = format;
@"Custom"
is not a valid date format string. Instead, pass in format.formatDetails
:
NSDateFormatter *formatter = [NSDate formatter : format.formatDetails : [NSTimeZone localTimeZone] : [NSLocale currentLocale]];
I should note that not using named arguments in Objective-C makes your code much harder to read.
来源:https://stackoverflow.com/questions/36753954/error-in-dateformat-returns-nil