简体   繁体   English

如何从plist文件读取自定义对象的数组?

[英]How to read array of custom objects from a plist file?

I have read many question how to save custom objects but I m not getting a idea. 我已经阅读了很多有关如何保存自定义对象的问题,但我不知道。 I don't know what to do next thats why I am asking a question. 我不知道下一步该怎么做,这就是为什么我要问一个问题。

Save custom object in plist file 将自定义对象保存在plist文件中

NSLog(@"%@",self.drawingView.pathArray);
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:self.drawingView.pathArray];
[arrayData writeToFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.plist"] atomically:YES];

Console o/p 控制台o / p

(
    "<PenTool: 0xa031f80;>",
    "<PenTool: 0x8b2b360;>",
    "<PenTool: 0xa03aca0;>",
    "<PenTool: 0x8b38780;>"
)

The above code works fine. 上面的代码工作正常。 Save in plist. 保存在plist中。 Now I want to get back all the objects from that plist. 现在,我想从该plist中取回所有对象。

Read from plist 从plist读取

NSData *data=[NSData dataWithContentsOfFile:[DOCUMENTPATH stringByAppendingPathComponent:@"1.plist"]];
self.pathArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];

Here I am getting a data. 在这里,我正在获取数据。 but not a array. 但不是数组。 I have read about that but there are saying you have to unarhive data. 我已经读过有关此内容,但有人说您必须取消归档数据。 But i don't have idea how to unarhive. 但是我不知道如何取消归档。

EDIT 编辑

I know I have to use below two method but not getting a idea. 我知道我必须使用以下两种方法,但没有任何想法。

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    return self;
}

- (void)encodeWithCoder:(NSCoder *)encoder {
}

Is there any other way to store custom objects in file. 还有其他方法可以在文件中存储自定义对象。

Your PenTool class needs to implement NSCoding . 您的PenTool类需要实现NSCoding This is described the Archives and Serialisations Programming Guide 这是对“ 存档和序列化编程指南”的描述

This question has a couple of useful examples. 这个问题有几个有用的例子。

These code snippets are from the Archives and Serialisations Programming Guide, the keys are strings. 这些代码段来自《存档和序列化编程指南》,键为字符串。

- (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;
}

基本上plist是一种在NSDictionary中保存数据的方法,因此我想您应该不理会数组,而在这种情况下开始使用字典

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM