【发布时间】:2015-10-21 18:26:51
【问题描述】:
我从 Web 服务收到 JSON 格式的日期。
我想将它存储在 core-data 中,在尝试这样做时出错后,读取 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 对象中,日期被定义为 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.
【问题讨论】:
-
我不明白。 NSLog (@"%@", object),将调用
[object description]。这不是因为 [object1 description] 和 [object2 description] 显示相同的值,它们来自同一类... -
我取出了 NSLogs
-
看起来
importItem.creationDate是NSDate *,对吗? -
我猜是的。但是,由于某种原因,它不会保存到核心数据中的日期字段中。
-
错误信息是:不可接受的属性值类型:property = "creationdate";所需类型 = NSDate;给定类型 = __NSCFString;值 = 2015-10-13 11:08:21