尝试将字符串传递给NSDateFormatter dateFromString方法时出现崩溃。
我检查了文档,但我没有看到任何可以解释出错的地方。
NSError * errorX;
NSDictionary * attributesDict = [[fileManager attributesOfItemAtPath:imgPath error:&errorX ] retain];
NSString *theDate = [[attributesDict objectForKey:@"NSFileCreationDate"] retain];
[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"];
NSDate *dateFromString = [[NSDate alloc] init];
dateFromString = [dateFormatter dateFromString:theDate];
崩溃来自最后一行。
erminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x1bd380'
有人能指出我离开的地方吗?
谢谢, -code
答案 0 :(得分:3)
[attributesDict objectForKey:@"NSFileCreationDate"]
将返回NSDate,而不是NSString。所以在这一点上,你已经拥有了你正在寻找的NSDate,没有必要使用NSDateFormatter来解析它。实际上,你当然不能因为dateFromString:需要一个字符串。
答案 1 :(得分:2)
从文件系统返回的对象是NSDate
,而不是NSString
。您已经有了一个日期对象,因此无需尝试将其转换回日期。
您发布的崩溃数据会告诉您崩溃的确切原因。您的应用程序将length
消息发送到日期对象的实例,并且日期对象不响应该消息(即NSDate
没有-length
方法)。我们知道dateFromString:
期望一个字符串并且需要解析字符串,所以我们可以假设它需要查询字符串的长度。所以你可以看到,你已经有了一个实际的日期对象。
答案 2 :(得分:0)
看起来像这一行
NSString * theDate = [[attributesDict objectForKey:@"NSFileCreationDate"] retain];
它已经为你返回一个NSDate而不是一个字符串。
如果你通过网络获取这些信息,根据格式,一些json解析器会自动将对象强制转换为NSDate。
答案 3 :(得分:0)
你确定吗? [attributesDict objectForKey:@“NSFileCreationDate”] 返回一个NSString对象? 它看起来像是返回一个NSDate;