【问题标题】:Objective C: Troubles archiving an NSDate目标 C:归档 NSDate 时遇到问题
【发布时间】:2012-09-27 20:14:49
【问题描述】:

我正在尝试将更改的 NSDate(开始日期的上午 8 点)保存在数据库中,以便在程序运行时随时检索。我正在使用对象归档。我以为我有正确的代码,但我似乎无法保存它。我没有收到任何错误,只是我在代码中输入的输出。我知道日期和时间是正确的,因为它们在 NSLog 中被视为输出。这是我的代码:

__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 被编码,存档器在哪里完成,我在哪里检查它是否有效。调试并没有那么明显,但老实说,在发现这种错误时,我不确定要寻找什么。我还能做些什么来解决这个问题?有哪些可能的解决方案?

【问题讨论】:

    标签: iphone objective-c key archive


    【解决方案1】:

    我认为这里的问题是您没有为writeToFile: 指定写入路径。

    试试这个:

    NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:@"firstDate.arch"];
    
    if ([__dataArea writeToFile:path atomically:YES] == NO){
        NSLog(@"archiving failed. ");
    }
    

    这会将您的文件写入临时目录,您可以简单地设置断点或记录路径变量以找出该位置的位置。 NSTemporaryDirectory() 只是一个例子,因为这个文件夹只是临时的,可以随时被系统删除。 Here is a category on NSFileManager 可能会为您提供更合适的路径。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多