字符串中的日期导致设备崩溃
我正在阅读 RSS 并从中读取一个元素:
2011 年 4 月 7 日星期四 13:37:41 +0000 我使用以下代码将接收到的字符串转换为 NSDate
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"]; // Thu, 18 Jun 2010 04:48:09 -0700
NSDate *date = [dateFormatter dateFromString:[self.currentDate stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
[item setObject:date forKey:@"date"];
代码,它在模拟器中完美运行,但在设备上崩溃了。原因是 NSDate 对象保持为零,当我将它添加到字典中时,它会使应用程序崩溃。
我读了很多关于这个问题的文章,但没有一个解决方案对我有用。我的意思是他们中的很多人都这样做了,但是在模拟器中......
任何帮助表示赞赏, 卢卡 ...
I am reading a RSS and from there an element:<pubDate>
Thu, 07 Apr 2011 13:37:41 +0000</pubDate>
I use the following code to turn the received string into NSDate
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"]; // Thu, 18 Jun 2010 04:48:09 -0700
NSDate *date = [dateFormatter dateFromString:[self.currentDate stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]];
[item setObject:date forKey:@"date"];
Code's working perfectly in simulator but on device it crashes. The reason is that NSDate object stays nil and when I'm adding it to the dictionary it crashes the app.
I read a lot around about this problem but none of the solutions worked for me. I mean lots of them did, but in simulator...
Any help appreciated,
Luka
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
检查两件事以消除模拟器和 ios 设备之间的差异。
iOS 设备区分大小写。所以你必须检查你的字符串是否有问题。
区域设置可能与您的模拟器和 iOS 不同。为了防止这种情况定义日期格式化程序的正确区域设置。
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
Check two things to eliminate the differences between simulator and ios device.
iOS Device is case sensitive. So you have to check your string if there is something wrong.
Locale setting can be different with your simulator and iOS. to prevent this define proper locale of date formatter.
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:usLocale];
通过以下方式测试格式化程序的行为
如果不是格式化程序的格式,则意味着您的 nsstring 是罪魁祸首。
您可以记录您要转换的字符串吗?可能是这个人有错
Test your formatter's behaviour by
If it's not the formatter's format it means that your nsstring is the one to blame.
Could you log the string that you are trying to convert? It's probably the one at fault