我已经阅读了很多关于如何保存自定义对象的问题,但我没有想到。我不知道下一步该做什么,这就是为什么我在问一个问题。
在plist文件中保存自定义对象
NSLog(@"%@",self.drawingView.pathArray);
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:self.drawingView.pathArray];
[arrayData writeToFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.plist"] atomically:YES];
控制台o / p
(
"<PenTool: 0xa031f80;>",
"<PenTool: 0x8b2b360;>",
"<PenTool: 0xa03aca0;>",
"<PenTool: 0x8b38780;>"
)
上面的代码工作正常。保存在plist中。现在我想从那个plist中取回所有对象。
从plist中读取
NSData *data=[NSData dataWithContentsOfFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.plist"]];
self.pathArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
我在这里获取数据。但不是数组。我已经读过这个,但有人说你必须 unarhive 数据。但我不知道如何放松。
修改
我知道我必须使用以下两种方法,但没有想到。
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
}
是否有其他方法可以在文件中存储自定义对象。
答案 0 :(得分:2)
您的PenTool
课程需要实施NSCoding
。这是Archives and Serialisations Programming Guide
这个question有几个有用的例子。
这些代码片段来自Archives and Serialisations Programming Guide,键是字符串。
- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.firstName forKey:ASCPersonFirstName];
[coder encodeObject:self.lastName forKey:ASCPersonLastName];
[coder encodeFloat:self.height forKey:ASCPersonHeight];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
_firstName = [coder decodeObjectForKey:ASCPersonFirstName];
_lastName = [coder decodeObjectForKey:ASCPersonLastName];
_height = [coder decodeFloatForKey:ASCPersonHeight];
}
return self;
}
答案 1 :(得分:0)
基本上plist是一种在NSDictionary中保存数据的方法,所以我想你应该单独保留数组并在这种情况下开始使用字典