After writing to archive and reading the NSDate object of custom class comes back as not an Objective-C object: Do I need to switch it to a string or should I be able to store it directly as an object within the class.
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];
this is the encoder/decoder:
- (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;
}
您正在归档对象数组,但您尝试仅取消归档一个“作业”对象:
homework *archivedHomework = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.