将JSON日期转换为日期以存储在核心数据中

时间:2015-10-21 18:26:52

标签: ios date core-data

我从JSON的Web服务收到日期。

我想将它存储在核心数据中,在尝试执行此错误后,请阅读JSON作为纯文本出现。

因此我实现了一些代码将其转换为日期。但是,日期仍然没有保存。不会抛出任何错误,但它会以黄色显示警告:initializing NSString with an expression of type NSDate

这是代码:

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];

    //Following line shows yellow warning:Incompatible pointer types initializing NSString with an expression of type NSDate.
                NSString *creationdatestr = importItem.creationDate;
 NSDate *creationdate = [dateFormatter dateFromString:creationdatestr];

值得注意的是,当我将creationdate和creationdatestr都记录到控制台时,它们看起来都如下所示,所以从dateFormatter可能没有发生任何事情。在任何情况下,两个版本都没有正确保存到日期字段中:

creation date:2015-10-16 11:05:57
creation date as date:2015-10-16 11:05:57

感谢任何建议。

修改

这是捕获JSON提要并将其分配给对象的方法。它似乎捕获JSON很好,但是,我不知道传入的JSON的数据类型是什么。毕竟,它只是到达文本,我不知道IOS如何确定输入文本的数据类型。

在IDItemFromServer对象中,date被定义为NSDate类型的属性。

- (NSArray *) convertFeedtoObject:(NSArray*)feed {
    // Create an array to store the locations
    NSMutableArray *_items = [[NSMutableArray alloc] init];  
    for (int i = 0; i < feed.count; i++) {
        NSDictionary *feedElement = feed[i];
        IDItemFromServer *newItem = [[IDItemFromServer alloc] init];
        newItem.name = feedElement[@"name"];
        newItem.date = feedElement(@"date");
NSLog(@"newItem.date");//this logs what looks like a date.

1 个答案:

答案 0 :(得分:0)

unset

您的警告/错误不是unset,而是unset

NSString *creationdatestr = importItem.creationDate;

因此这行代码是错误的。

什么是NSString?它是你的NSDate子类吗?如果是这样,您尝试将现有NSDate *creationdate = [dateFormatter dateFromString:creationdatestr]; 对象转换为importItem,但这不起作用,因为它已经是NSManagedObject

相关问题