Cocoa Touch serializing object. Trying to read data member of custom class after being decoded causes program to crash
I'm having what seems to be a rather strange error when attempting to encode and decode an object I created. I believe I made the object and all the objects it contains conform to NSCoding and NSCopying. I'm attempting to encode a NSMutableArray filled with "Goals" which have a NSString title and a NSMutableArray of "ActionSteps" which also conform to the protocols. I can encode the objects just fine and when I decode the objects they respond to function calls that don't deal with the data members, but when I try to read the title of on of the "Goals" the program crashes and I get this error message:
-[__NSArrayM isEqualToString:]: unrecognized selector sent to instance followed by a stack trace and finally: Program received signal: “SIGABRT”.
I get the same error message when I attempt to access the titles of the "ActionSteps" inside the goals.
Here is my code for the "goal" class for conforming to the protocols.
#pragma mark NSCoding
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:goalName forKey:GoalNameKey];
[encoder encodeObject:actionSteps forKey:ActionStepsKey];
}
This time I tried printing out whatever the decoder is returning as it should be an NSString and I got the same crash.
- (id)initWithCoder:(NSCoder *)decoder {
if (self = [super init]) {
goalName = [[decoder decodeObjectForKey:GoalNameKey] retain];
NSLog((NSString *)开发者_开发问答[decoder decodeObjectForKey:GoalNameKey]);
actionSteps = [[decoder decodeObjectForKey:ActionStepsKey] retain];
}
return self;
}
#pragma mark -
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone {
Goal *copy = [[[self class] allocWithZone: zone] init];
copy.goalName = [[self.goalName copyWithZone:zone] autorelease];
copy.actionSteps = [[self.actionSteps copyWithZone:zone] autorelease];
return copy;
}
Here is the code for encoding the main NSMutableArray that contains all my "Goals":
[NSKeyedArchiver archiveRootObject:goalViewController.goals toFile:[self dataFilePath]];
and for decoding:
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
goalViewController.goals = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
else {
goalViewController.goals = [[NSMutableArray alloc]init];
}
the error occurs when I try to read from the title of a "Goal" after It has been decoded
label.text = self.goal.goalName;
You have ActionStepsKey
in both decode calls:
goalName = [[decoder decodeObjectForKey:ActionStepsKey] retain];
actionSteps = [[decoder decodeObjectForKey:ActionStepsKey] retain];
The first one should have GoalNameKey
:
goalName = [[decoder decodeObjectForKey:GoalNameKey] retain];
actionSteps = [[decoder decodeObjectForKey:ActionStepsKey] retain];
精彩评论