NSString 到 NSDate 转换时程序崩溃
我有一个很好的小 for 循环,但我被困住了。恐怕我已经代码盲了,或者是对象盲了?我不知道...我的应用程序在标记为 -->
的行崩溃,我不明白为什么。
for(int search = 2; search<10; search=search+2) {
NSString *arrayTime = [searchArray objectAtIndex:search];
arrayTime = [@" " stringByAppendingString:arrayTime];
NSString *arrayDate = [currentDate stringByAppendingString: arrayTime];
--> NSDate *compareTime = [wholeDateTimeFormat dateFromString: arrayDate];
NSDate *searchCompareTime = [wholeDateTimeFormat dateFromString:searchTime];
NSLog(@"Start: %@ --- search: %@", compareTime, searchCompareTime);
float compareResult = [searchCompareTime timeIntervalSinceDate: compareTime];
NSLog(@"compareReslut: %f", compareResult);
}
一些解释:currentDate
的格式如下:@"yyyy-MM-dd"
。 wholeDateTimeFormat
的格式如下:@"yyyy-MM-dd HH:mm"
。
然后我需要将其转换为 NSDate 对象;这就是失败的地方,到目前为止我不知道为什么。我把这归咎于我生病了。 :) 我没有构建错误,但它仍然在我身上消失。为什么? :DI 非常感谢我能得到的所有帮助。
I have a nice little for-loop and I am stuck. I am afraid I've gone code blind, or is it object blind? I can't tell... My app crashes on the line marked -->
and I can't see why.
for(int search = 2; search<10; search=search+2) {
NSString *arrayTime = [searchArray objectAtIndex:search];
arrayTime = [@" " stringByAppendingString:arrayTime];
NSString *arrayDate = [currentDate stringByAppendingString: arrayTime];
--> NSDate *compareTime = [wholeDateTimeFormat dateFromString: arrayDate];
NSDate *searchCompareTime = [wholeDateTimeFormat dateFromString:searchTime];
NSLog(@"Start: %@ --- search: %@", compareTime, searchCompareTime);
float compareResult = [searchCompareTime timeIntervalSinceDate: compareTime];
NSLog(@"compareReslut: %f", compareResult);
}
Some explanations: currentDate
is formatted like this: @"yyyy-MM-dd"
.
And wholeDateTimeFormat
is formatted like this: @"yyyy-MM-dd HH:mm"
.
Then I need to convert it to an NSDate object; this is where is fails, and I have no idea why as of now. I blame it on the fact that I am falling ill. :)
I have no build errors and still it dies on me. Why? :D I am grateful for all the help I can get.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用 NSDateFormatter - 它会自动完成这一切!
(我本想尝试更具体 - 但你的代码让我有点困惑)。
无论如何 - 像这样:
Just use NSDateFormatter - it does all this automatically!
(I was going to try to be more specific - but your code has me a bit confused).
Anyway - something like:
好的,问题解决了。
这个问题超出了这段代码的范围,而且我怀疑我已经变得代码盲了。
我让一个朋友看代码,他花了 2 秒才发现问题。
我在 for 循环之前释放了日期格式化程序。
感谢您的所有投入!
Ok, problem solved.
The problem was outside the scope of this code and as I suspected I had become code blind.
I got a friend to watch the code and it took him 2 secs to spot the problem.
I released the dateformatters before the for-loop.
Thanks for all the input!