Why i cannot convert NSString to NSData
In my People.h, I implement NSCoding, In People.m:
@implementation People
@synthesize name;
- (void) encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:name forKey:@"name"];
}
-(id) initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.name = [aDecoder decodeObjectForKey:@"name"];
}
return self;
}
@end
In my viewDidLoad function of co开发者_如何学编程ntroller.
People *people1 = [[People alloc] init];
people1.name = @"kevin";
NSData *saveData = [NSKeyedArchiver archivedDataWithRootObject:people1];
NSString *saveDataString = [[NSString alloc] initWithData:saveData encoding:NSASCIIStringEncoding];
NSData *resultData = [saveDataString dataUsingEncoding:NSASCIIStringEncoding];
People *people2 = [NSKeyedUnarchiver unarchiveObjectWithData:resultData];
NSLog(@"%@",people2.name);
[super viewDidLoad];
Why i got a null at the end of this function. Did I hava some mistakes?
Thanks!
It looks like you were trying to unarchive Peopla out of NSString, try this
NSData *saveData = [NSKeyedArchiver archivedDataWithRootObject:people1];
People *people2 = [NSKeyedUnarchiver unarchiveObjectWithData:saveData];
精彩评论