2013-06-23 28 views
1

我有一個文件,我需要根據文件的創建日期替換此文件,因此如果此文件的創建日期在2013年6月23日之前,那麼我將刪除它並添加新文件,以便新創建日期爲2013年6月23日,但如果創建日期等於或等於2013年6月23日,則不執行任何操作。在iOS中檢查文件創建日期時的問題

將以上邏輯應用於開發環境時,一切正常無問題,但是當我將其部署到生產(iTunes)時,條件= true意味着代碼始終在2013年6月23日之前進入條件並刪除文件並創建一個新文件。

我的代碼是:

if ([fileManager fileExistsAtPath:writableDBPath]) { 
NSDate *creationDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:writableDBPath error:&error] objectForKey:NSFileCreationDate]; 

BOOL result = NO; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd"]; 
NSDate *issueDate = [dateFormatter dateFromString:@"2013-05-22"]; 

NSDateComponents *creationDateComponents = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:creationDate]; 
NSDateComponents *issueDateComponents = [CURRENT_CALENDAR components:DATE_COMPONENTS fromDate:issueDate]; 

NSTimeInterval secondsBetweenCreationIssue = [[CURRENT_CALENDAR dateFromComponents:creationDateComponents] timeIntervalSinceDate:[CURRENT_CALENDAR dateFromComponents:issueDateComponents]]; 

if ((lround((secondsBetweenCreationIssue/86400))) <= 0) { 
    result = YES; 
} 
else{ 
    result = NO; 
} 
//if the file is OLD 
if (result) { 
    [fileManager removeItemAtPath:writableDBPath error:&error]; 
} 
+1

當你說開發/生產,你的意思是模擬器/設備?你是否考慮到任何地方的語言環境? – Wain

+0

不是它的開發/生產或開發版本和商店版本 – OXXY

+0

它在設備和模擬器在開發階段運行良好,但商店的版本不起作用 – OXXY

回答

2

第一件事,你不應該使用NSDateFormatter這樣。 NSDateFormatter創建起來很昂貴,而且使用起來很昂貴。既然你知道你的約會完美,我建議你使用NSDateComponents創建issueDate

NSDateComponents *issueDateComponents = [[NSDateComponents alloc] init]; 
issueDateComponents.day = 23; 
issueDateComponents.month = 6; 
issueDateComponents.year = 2013; 
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdenfier:NSGregorianCalendar]; 
NSDate *issueDate = [gregorian dateFromComponents:issueDateComponents]; 

(請注意,我用的是公曆,因爲你的日期似乎是從該日曆的用戶當前日曆可能是一個又一個,那個日期將不起作用)。

第二件事。而不是硬編碼在一天的秒數,你應該提取日期組件,並用它們來比較:

if ([fileManager fileExistsAtPath:writableDBPath]) { 
    NSDate *creationDate = [[[NSFileManager defaultManager] attributesOfItemAtPath:writableDBPath error:&error] objectForKey:NSFileCreationDate]; 

    // Here should be the code from the previous example 

    // Again, use a gregorian calendar, not the user current calendar, which 
    // could be whatever. I'm not sure every calendar has the same days and 
    // months, so we better be sure. 
    NSDateComponents *creationDateComponents = [gregorian components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:creationDate]; 
    creationDate = [gregorian dateFromComponents:creationDateComponents]; 

    if ([creationDate compare:issueDate] == NSOrderedAscending) { 
    [fileManager removeItemAtPath:writableDBPath error:&error]; 
    } 
} 

(你應該檢查時區影響這個計算以任何方式,我不確定)。

我認爲你使用你的代碼看到的問題是使用用戶當前日曆(和區域設置),它可能會影響NSDateFormatter解析日期的方式以及你對時間間隔的複雜計算。

另一件讓我感到困惑的事情是,如果secondsBetweenCreationIssue只有不到1天的時間,那麼它看起來像只會設置爲YES,但日期最早的日期不會通過測試。

希望它有幫助。