2010-07-07 85 views
1

我保存的日期已经转换为一个字符串到应用程序退出时的plist。当viewDidLoad运行时,我试图读取返回的字符串并将其转换回日期。该字符串保存到plist并正确读入,但不会转换回日期。我正在使用NSDate日期命令给出的标准格式。 Time1始终为空。NSDate dateFromString返回NULL

输出看起来像这样:

time1string = 2010-07-07 13:47:12 -0500 
time1 = (null) 

的代码看起来是这样的:

- (void)applicationWillTerminate:(NSNotification *)notification { 
NSMutableArray *array = [[NSMutableArray alloc] init]; 

[array addObject: [NSString stringWithFormat:@"%@", time1]]; 

[array writeToFile:[self dataFilePath] atomically:YES]; 
[array release]; 

NSLog(@"APP Terminating, Persisting Data"); 

}

- (无效)viewDidLoad中{

NSLog(@"View did load"); 
NSString *filePath = [self dataFilePath]; 
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 
    NSArray *array = [[NSArray alloc] initWithContentsOfFile:filePath]; 

    NSString *time1string = [array objectAtIndex:1]; 
    NSLog(@"time1string = %@",time1string); 
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss Z"]; 
    time1 = [dateFormat dateFromString:time1string]; 
    NSLog(@"time1 = %@",time1); 
    [dateFormat release]; 
    [array release]; 

} 
UIApplication *app = [UIApplication sharedApplication]; 
[[NSNotificationCenter defaultCenter] addObserver:self 
             selector:@selector(applicationWillTerminate:) 
              name:UIApplicationWillTerminateNotification 
              object:app]; 
[super viewDidLoad]; 

}

+0

你可以显示time1的声明吗? – falconcreek 2010-07-07 19:34:05

+0

从FAQ >当您决定哪个答案对您最有帮助时,通过单击答案左侧的复选框大纲将其标记为接受的答案。这让其他人知道你已经收到了你的问题的一个很好的答案。这样做很有帮助,因为它向其他人表明您从社区中获得价值。 (如果你不这样做,人们会经常礼貌地要求你回去接受更多你的问题的答案!)> – falconcreek 2010-07-08 22:48:09

回答

8

它看起来没有解析,因为你使用的日期格式错误。请尝试使用@"yyyy-MM-dd HH:mm:ss Z"代替。 hh格式需要1-12小时,而HH使用0-23。

查看Locale Data Markup Language可以在这里使用的所有图案的全部参考(通过Data Formatters reference)。

+0

这个答案似乎是合法的。我试过其他答案,指出有关区域设置和所有,但都没有工作。这就像一个魅力。链接也非常有帮助。 – tyegah123 2014-06-03 06:46:02