1

我正在尝试调试此应用程序,但存在一个大问题。当我尝试将数组保存到数据文件时,一切正常。但是,如果我关闭应用程序并重新打开数组中的布尔值,则变为 nil。这是保存数组的代码:

NSString *filePath = [self dataFilePath];
[NSKeyedArchiver archiveRootObject:self.alist toFile:filePath];
NSLog(@"%@", self.alist.description);

- (NSString*)dataFilePath
{
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [docDir stringByAppendingPathComponent:@"AssignmentInfo.data"];
    NSFileHandle *file = [NSFileHandle fileHandleForWritingAtPath:filePath];

    if (!file) {
        if (![[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]) {
        }
        else
            file = [NSFileHandle fileHandleForWritingAtPath:filePath];

    }

    return filePath;
}

数组内部是我创建的一个自定义类...这是该类的代码:

-(NSString *)description
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    dateFormatter.timeZone = [NSTimeZone defaultTimeZone];
    dateFormatter.timeStyle = NSDateFormatterShortStyle;
    dateFormatter.dateStyle = NSDateFormatterShortStyle;
    NSString *dateTimeString = [dateFormatter stringFromDate: self.dateTime];
    return [NSString stringWithFormat:@"Class: %@\r Assignment Title: %@ \rAssignment Description: %@ \rDue: %@ \r%s", self.className, self.assignmentTitle, self.assignmentDescription, dateTimeString,self.notifcationStatus ? "Notification On" : "Notification Off"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init];

    self.className = [aDecoder decodeObjectForKey:@"className"];
    self.assignmentTitle = [aDecoder decodeObjectForKey:@"assignmentTitle"];
    self.assignmentDescription = [aDecoder decodeObjectForKey:@"assignmentDescription"];
    self.dateTime = [aDecoder decodeObjectForKey:@"dateTime"];
    self.notifcationStatus = [aDecoder decodeBoolForKey:@"notifcationStatus"];

    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.className forKey:@"className"];
    [aCoder encodeObject:self.assignmentTitle forKey:@"assignmentTitle"];
    [aCoder encodeObject:self.assignmentDescription forKey:@"assignmentDescription"];
    [aCoder encodeObject:self.dateTime forKey:@"dateTime"];
    [aCoder encodeBool:self.notifcationStatus forKey:@"notificationStatus"];
}

self.notifcationStatus是变成 的数组FALSE

4

1 回答 1

3

它有助于在归档和取消归档时使用相同的密钥:

self.notifcationStatus = [aDecoder decodeBoolForKey:@"notifcationStatus"];

...

[aCoder encodeBool:self.notifcationStatus forKey:@"notificationStatus"];

您正在使用两个不同的键:notifcationStatus解码时和notificationStatus编码时。(缺少i)。

在这种情况下,最好使用 #define 宏或等效宏来确保在两个地方使用相同的键(帽子提示:@godel9):

// somewhere in your .h, for instance:
#define kNotificationStatus @"notificationStatus"


self.notifcationStatus = [aDecoder decodeBoolForKey: kNotificationStatus];

...

[aCoder encodeBool:self.notifcationStatus forKey: kNotificationStatus];
于 2013-10-27T15:28:16.510 回答