将字符串转换为NSDate问题:[__NSDate Length]无法识别已选中 [英] converting string to NSDate issue: [__NSDate Length] unrecognized selected

查看:245
本文介绍了将字符串转换为NSDate问题:[__NSDate Length]无法识别已选中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

indexNumber.row 是一个类似 2012-03-09 23:00:00 +0000 的日期。我尝试了一些不同的方法将我的日期转换为 NSDate ,但我一直收到标题错误。

indexNumber.row is a date like 2012-03-09 23:00:00 +0000. I've tried a handful of different ways to get my date into an NSDate, but I keep getting the title error.

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row];

// Convert string to date object
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:inputString ];
NSLog(@"date format is: %@", date);

我发现以下错误的任何想法:

Any ideas why I get the following error:


由于未捕获的异常'NSInvalidArgumentException'终止应用程序,原因:' - [__ NSDate长度]:无法识别的选择器发送到实例0x6ca0c60'

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDate length]: unrecognized selector sent to instance 0x6ca0c60'


推荐答案

您收到该错误是因为您将 NSDate 对象传递给 dateFromString:

You get that error because you are passing a NSDate object to dateFromString:.

添加 NSLog ,你会看到:

NSString *inputString = [self.measurements objectAtIndex:indexNumber.row];
if ([inputString isKindOfClass:[NSDate class]]) {
    NSLog(@"inputString is of type NSDate");
}

此外,以下是重现错误的方法:

Also, here is how to reproduce your error:

NSString *inputString = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *date = [dateFormatter dateFromString:inputString];

这意味着数组 self.measurements 包含 NSDate 对象而不是 NSString 对象。

That means that the array self.measurements contains NSDate objects and not NSString objects.

当您更正当前问题时,您可能会遇到一个新问题,因为您没有使用正确的日期格式。要解析类型为: 2012-03-09 23:00:00 +0000 的日期字符串,您应使用以下日期格式:

When you correct your current problem, you will probably encounter a new one because you don't use the correct date format. To parse date strings of type: 2012-03-09 23:00:00 +0000 you should use the following date format:

[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zz"];

这篇关于将字符串转换为NSDate问题:[__NSDate Length]无法识别已选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆