2012-09-27 35 views
1

我試圖保存改變的NSDate(開始日期的上午8點)在數據庫中進行檢索隨時程序運行。我正在使用對象歸檔。我認爲我有正確的代碼,但我似乎無法保存它。我沒有收到任何錯誤,只是我輸入到代碼中的輸出。我知道日期和時間是正確的,因爲它們在NSLog中被看作是輸出。這裏是我的代碼:目標C:麻煩歸檔一個NSDate

__dataArea = [NSMutableData data]; 
__unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:__dataArea]; 
__archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:__dataArea]; 

__iDates = [[BCimportantDates alloc] initWithCoder:[NSKeyedUnarchiver unarchiveObjectWithFile: @"firstDate.arch"]]; 

if ((__iDates.firstDate == nil)){ 

    NSDate *date = [NSDate date]; 
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar]; 
    NSDateComponents *components = [gregorian components: NSUIntegerMax fromDate: date]; 
    NSLog(@"the date %@",date); 
    [components setHour: 3]; 
    [components setMinute: 00]; 
    [components setSecond: 00]; 
    __newDate = [gregorian dateFromComponents: components]; 
    [__iDates setFirstDate: __newDate]; 
    NSLog(@"%@",__iDates.firstDate); 
    [__iDates encodeWithCoder: __archiver]; 
    [__archiver finishEncoding]; 
    if ([__dataArea writeToFile:@"firstDate.arch" atomically:YES] == NO){ 
     NSLog(@"archiving failed. "); 
    } 
} 

,這裏是的編碼器和解碼器的功能BCimportantDates.m內實現:

- (void) encodeWithCoder:(NSCoder *)encoder{ 
    [encoder encodeObject: __firstDate forKey: kfirstDateKey]; 
} 

- (id) initWithCoder: (NSCoder *) decoder{ 
    if (self = [super init]) { 
    self.firstDate = [decoder decodeObjectForKey:kfirstDateKey]; 
    } 
    return self; 
} 

我使用斷點試圖在那裏__iDates進行編碼,其中歸檔整理,我在哪裏檢查它是否工作。調試沒有那麼顯露,但說實話,我不確定在找到這種錯誤時要尋找什麼。我還能做些什麼來弄清楚這個問題?有什麼可能的解決方案?

回答

0

我覺得這裏的問題是,你沒有指定爲writeToFile:寫的路徑。

試試這個:

NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"firstDate.arch"]; 

if ([__dataArea writeToFile:path atomically:YES] == NO){ 
    NSLog(@"archiving failed. "); 
} 

這將文件寫入到一個臨時目錄,你可以簡單地設置一個斷點或日誌路徑變量,以找出這個位置。 NSTemporaryDirectory()只是一個例子,因爲這個文件夾只是臨時的,可以隨時被系統刪除。 Here is a category on NSFileManager這可能會爲您提供更合適的路徑。