0

我被困在一些愚蠢的事情上。这个应用程序是一个 OSX 核心数据应用程序。我正在调用操作表来处理日期。关闭工作表后,所选日期正确显示在屏幕上。但是,我不知道如何保存日期。

任何帮助表示赞赏。这是我在 AppDelegate.m 中使用的代码:

NSDate *theDate = [self.purchaseDatePicker dateValue];
    if (theDate)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        NSString *formattedDateString;

        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterNoStyle];

        formattedDateString = [formatter stringFromDate:theDate];

        [self.purchaseDate setStringValue: formattedDateString];
        self.item.purchaseDate = theDate;
        [self.item setPurchaseDate:theDate];
        [self.item setPurchaseDate:self.item.purchaseDate];

        NSLog(@"theDate is %@", theDate); <-- this is fine.
        NSLog(@"item.purchaseDate is %@", self.item.purchaseDate); <-- this returns NULL

        NSError *error = nil;
        NSManagedObjectContext *moc = _coreDataController.mainThreadContext;
        if (![moc save:&error])
        {
            [[NSApplication sharedApplication] presentError:error];
        }
            }
}
4

1 回答 1

0

我发现这里的答案很有帮助,但这篇文章真的让我思考。所以今天,代码如下所示,效果很好!!

1.

[itemArrayController setValue: [DatePicker1 dateValue] forKeyPath: @"selection.date1"];

2.

  if ([itemArrayController valueForKeyPath: @"selection.date1"] == NULL) {
        date1 = [NSDate date];
        [datePicker1 setDateValue: date1];
    } else {
        [datePicker1 setDateValue: [itemArrayController valueForKeyPath: @"selection.date1"]];
        date1 = [itemArrayController valueForKeyPath: @"selection.date1"];
    }
于 2013-04-17T00:12:27.250 回答