归档数组后,BOOL变为false

时间:2013-10-27 15:03:51

标签: ios nsmutablearray

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

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的数组。

1 个答案:

答案 0 :(得分: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];