【问题标题】:NSCFCalendar toDate is returning nilNSCC 迄今为止的日历返回 nil
【发布时间】:2012-12-29 12:23:39
【问题描述】:

我正在解析一个日期,并希望将其转换为用户当前所在的时区。此外,我想显示一个倒计时,显示距离特定日期还有多少天。这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";

    TableCellView *cell = (TableCellView *)[tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if(cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"TableCellView" owner:self options:nil];
        cell = tblCell;
    }

    NSString *cellstring = [NSString stringWithFormat:@"%@", [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"title"]];
    NSString *cellnumber = [NSString stringWithFormat:@"%@", [[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"number"]];

    NSString *epinumber = [cellnumber stringByReplacingOccurrencesOfString:@"-" withString:@""];

    NSString *celldescription = [NSString stringWithFormat:@"%@",[[self.parseResults objectAtIndex:indexPath.row] objectForKey:@"date"]];

    //NSLog(@"%@", celldescription);
    //celldescription returns a value


    NSString *finalString = [celldescription stringByReplacingOccurrencesOfString:@"EST" withString:@""];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

    [dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];

    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
    // this is imporant - we set our input date format to match our input string
    // if format doesn't match you'll get nil from your string, so be careful
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];
    NSDate *dateFromString = [[NSDate alloc] init];
    // voila!
    dateFromString = [dateFormatter dateFromString:finalString];

    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];

    [dateFormatter1 setDateFormat:@"EEE, dd MMM yyyy HH:mm aaa"];

    NSString *dateDisplay = [dateFormatter1 stringFromDate:dateFromString];

    [dateFormatter release];

    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];

    int units = NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    NSDateComponents *components = [calendar components:units fromDate:[NSDate date] toDate:dateFromString options:0];
    NSString *string = [NSString stringWithFormat:@"%d", [components day]];

    if (indexPath.row == 0) {
        cell.cellText.textColor = [UIColor redColor];
    } else {
        cell.cellText.textColor = [UIColor blackColor];
    }

    [cell setLabelText:cellstring];
    [cell setDateText:dateDisplay];
    [cell setCountText:string];
    [cell setNumberText:epinumber];


    return cell;
}

但我总是收到以下错误:

2012-12-29 13:10:23.139 spncountdown[87678:c07] *** -[__NSCFCalendar components:fromDate:toDate:options:]: toDate cannot be nil
I mean really, what do you think that operation is supposed to mean with a nil toDate?
An exception has been avoided for now.
A few of these errors are going to be reported with this complaint, then further violations will simply silently do whatever random thing results from the nil.
Here is the backtrace where this occurred this time (some frames may be missing due to compiler optimizations):
(
    0   CoreFoundation                      0x012c1c78 -[__NSCFCalendar components:fromDate:toDate:options:] + 200
    1   spncountdown                        0x000340bf -[SixthViewController convertWork] + 831
    2   spncountdown                        0x00033c14 -[SixthViewController tableView:cellForRowAtIndexPath:] + 820
    3   UIKit                               0x020988fb -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:withIndexPath:] + 412
    4   UIKit                               0x020989cf -[UITableView(UITableViewInternal) _createPreparedCellForGlobalRow:] + 69
    5   UIKit                               0x020811bb -[UITableView(_UITableViewPrivate) _updateVisibleCellsNow:] + 1863
    6   UIKit                               0x02091b4b -[UITableView layoutSubviews] + 241
    7   UIKit                               0x0202e2dd -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 279
    8   libobjc.A.dylib                     0x030ad6b0 -[NSObject performSelector:withObject:] + 70
    9   QuartzCore                          0x01dcdfc0 -[CALayer layoutSublayers] + 240
    10  QuartzCore                          0x01dc233c _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 468
    11  QuartzCore                          0x01dc2150 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 26
    12  QuartzCore                          0x01d400bc _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 324
    13  QuartzCore                          0x01d41227 _ZN2CA11Transaction6commitEv + 395
    14  QuartzCore                          0x01de3b50 +[CATransaction flush] + 52
    15  UIKit                               0x01ff3edf _afterCACommitHandler + 132
    16  CoreFoundation                      0x0127aafe __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30
    17  CoreFoundation                      0x0127aa3d __CFRunLoopDoObservers + 381
    18  CoreFoundation                      0x012587c2 __CFRunLoopRun + 1106
    19  CoreFoundation                      0x01257f44 CFRunLoopRunSpecific + 276
    20  CoreFoundation                      0x01257e1b CFRunLoopRunInMode + 123
    21  GraphicsServices                    0x03b127e3 GSEventRunModal + 88
    22  GraphicsServices                    0x03b12668 GSEventRun + 104
    23  UIKit                               0x01fddffc UIApplicationMain + 1211
    24  spncountdown                        0x00003222 main + 130
    25  spncountdown                        0x00003155 start + 53
)

【问题讨论】:

  • nslog 最终字符串并让我们知道值。
  • @AnoopVaidya NSLog of finalString:2013 年 2 月 27 日星期三 21:00:00
  • @Perception 我知道它在某个地方返回 nil,但为什么它是 Nil?
  • @AmiiQo - 在通话前记录您的 dateFromStringdateDisplay 对象。它们的价值是什么?

标签: iphone ios uitableview nsdate


【解决方案1】:

很明显,您的dateFromStringnil,这可能是因为日期格式问题。尝试打印出格式化的字符串并理解为什么NSDateFormatter 没有正确解析它。

【讨论】:

    【解决方案2】:

    您的NSLog 打印:Wed, 27 Feb 2013 21:00:00

    使用此代码:

    NSString *finalString=@"Wed, 27 Feb 2013 21:00:00";
    NSDateFormatter *dateFormatter2=[NSDateFormatter new];
    [dateFormatter2 setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss"];
    
    NSLog(@"finalString: %@",[dateFormatter2 dateFromString:finalString]);
    
    NSDate *dateFromString =[dateFormatter2 dateFromString:finalString];
    
    [dateFormatter2 setDateFormat:@"dd MMM YYYY"];
    NSLog(@"dateFromString  : %@",[dateFormatter2 stringFromDate:dateFromString]);
    

    输出:

    finalString: 2013-02-27 15:30:00 +0000
    dateFromString  : 27 Feb 2013
    

    【讨论】:

    • 谢谢,但 dateFromString 已经返回 nil,正如 Stavash 指出的那样。这怎么可能?
    • 我同意@AnoopVaidya - 这正是我要指出的问题
    • 谢谢,原来解析有问题。我的字符串包含空格,我必须用 [finalString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] 修剪它
    【解决方案3】:

    我为我解决了这个问题。我希望这对任何人都有帮助。我的问题是注释的代码。我用这个注释代码下面的新书面代码解决了这个问题。代码如下:

    //    NSDateFormatter *df = [[NSDateFormatter alloc] init];
        //    df.dateStyle = NSDateFormatterMediumStyle;
        //
        //    NSCalendar *calendar = [NSCalendar currentCalendar];
        //    int year   =    [[calendar components:NSYearCalendarUnit  fromDate:[datePickerView date]] year];
        //    int month  =    [[calendar components:NSMonthCalendarUnit fromDate:[datePickerView date]] month];
        //    int day    =    [[calendar components:NSDayCalendarUnit   fromDate:[datePickerView date]] day];
        //    
    
        NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[datePickerView date]];
        NSInteger day = [components day];
        NSInteger month = [components month];
        NSInteger year = [components year];
    
        date = [NSString stringWithFormat:@"%d-%d-%d",year,month, day];
        NSLog(@"Updated Date: %@",date);
    

    【讨论】:

      【解决方案4】:

      我解决了我的问题。在下面的示例中,我将 'nil' 传递给 'date'。

      NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
      NSDateComponents *comps = [gregorian components:NSWeekdayCalendarUnit fromDate:date];
      

      【讨论】:

        猜你喜欢
        • 2017-08-14
        • 2013-03-06
        • 1970-01-01
        • 1970-01-01
        • 2014-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-07
        相关资源
        最近更新 更多