2010-07-07 86 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