0

在写入存档并读取自定义类的 NSDate 对象后,它不是一个 Objective-C 对象:我需要将其切换为字符串还是应该能够将其直接存储为类中的对象。

anArray = [[NSMutableArray alloc] initWithObjects:nil];
self.title = @"Homework APP";
NSString *filePath = [self dataFilePath];
NSDate *datetoday=[NSDate date];
//Create an object for archiving
homework *myHomework = [[homework alloc] init];
myHomework.classname = @"Physics";
myHomework.title = @"HW1";
myHomework.description = @"Test";
myHomework.duedate = datetoday;
myHomework.notify = TRUE;
homework *myHomework2 = [[homework alloc] init];
myHomework2.classname = @"Computer";
myHomework2.title = @"HW2";
myHomework2.description = @"Test";
myHomework2.duedate = datetoday;
myHomework2.notify = FALSE;

NSMutableArray *myHomeworksArray = [[NSMutableArray alloc] initWithObjects:myHomework, myHomework2, nil];
anArray = myHomeworksArray;
//Archive my object
[NSKeyedArchiver archiveRootObject:myHomeworksArray toFile:filePath];

//Unarchive my object to check
homework *archivedHomework = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

这是编码器/解码器:

- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.classname forKey:@"classname"];
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.description forKey:@"description"];
    [aCoder encodeObject:self.duedate forKey:@"duedate"];
    [aCoder encodeBool:self.notify forKey:@"notify"];

}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super init]; //call class
    if (self) { //makes sure it exists
    self.classname = [aDecoder decodeObjectForKey:@"classname"];
    self.title = [aDecoder decodeObjectForKey:@"title"];
    self.description = [aDecoder decodeObjectForKey:@"description"];
    self.duedate = [aDecoder decodeObjectForKey:@"duedate"];
    self.notify = [aDecoder decodeBoolForKey:@"notify"];
    }

    return self;

}
4

1 回答 1

2

您正在归档对象数组,但您试图仅取消归档一个“家庭作业”对象:

homework *archivedHomework = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
于 2013-10-21T17:41:44.873 回答