简体   繁体   English

如何将类对象数组保存到Plist(iPhone开发)

[英]How can I save Array of Class Objects in to a Plist(Iphone Development)

I have a question related to save an array of Class objects to a plist And then get it back. 我有一个问题,涉及将Class对象的数组保存到plist中,然后将其取回。

For example i have a class "A" with two Nsstring and some int values. 例如,我有一个带有两个Nsstring和一些int值的类“ A”。

I have an array of Class A objects. 我有一个Class A对象数组。

How can i save this array in to plist. 我如何将这个数组保存到plist中。

I can Done store a simple Array(Array of Strings) in to Plist.There is No Error. 我可以将一个简单的数组(字符串数组)存储到Plist中。没有错误。

But When I store this "Array of Objects" It cant be done. 但是,当我存储此“对象数组”时,它无法完成。

Thanks in Advance. 提前致谢。

First convert your NSArray to NSDictionary as given here . 首先将您的NSArray转换为NSDictionary,如此处所示

Then use NSDictionary 's writeToFile:atomically: to store that as Plist. 然后使用NSDictionarywriteToFile:atomically:将其存储为Plist。

For this, your class must be conform to NSCoding protocol. 为此,您的类必须符合NSCoding协议。

Or otherwise, you can write your NSArray itself directly to plist without converting to NSDictionary. 否则,您可以将NSArray本身直接写入plist,而无需转换为NSDictionary。 But anyhow, the class should conform to NSCoding protocol. 但是无论如何,该类应符合NSCoding协议。

You cant save objects to Plists. 您无法将对象保存到Plist。 It wont ever work, you would only ever be able to save internal variables to a plist. 它永远都行不通,您只能将内部变量保存到plist中。 It you want to save objects, you need to first make your class NSCoding compliant. 如果要保存对象,则需要首先使您的类NSCoding兼容。 This is a good link explaining it http://samsoff.es/posts/archiving-objective-c-objects-with-nscoding But it doesn't mention objects within objects but its basically just another level. 这是一个很好的链接,解释它http://samsoff.es/posts/archiving-objective-c-objects-with-nscoding但它没有提到对象内的对象,而基本上只是另一层。 You need to make sure any object that is within an object you are saving is NSCoding compliant as well, all the way down the chain. 您需要确保要保存的对象中的任何对象在整个链中也都符合NSCoding。 Then you need to use NSKeyedArchiver to save them. 然后,您需要使用NSKeyedArchiver来保存它们。 I wrote a nice manager class that will take care of all of this for you as long as your objects ar NSCoding compliant. 我编写了一个不错的管理器类,只要您的对象符合NSCoding,它就会为您解决所有这些问题。 its available right here https://github.com/caranicas/Save-Manager enjoy! 它可以在这里https://github.com/caranicas/Save-Manager享受!

Indicate the .plist path to the class variable correctly 正确指示类变量的.plist路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"patientList.plist"];
[myPatients writeToFile:path atomically:YES];

use the above i hope this wil be usefull 使用上面的我希望这会有用

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

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