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

不打扰是莪最后的温柔 提交于 2019-12-08 06:56:36

问题


I have a question related to save an array of Class objects to a plist And then get it back.

For example i have a class "A" with two Nsstring and some int values.

I have an array of Class A objects.

How can i save this array in to plist.

I can Done store a simple Array(Array of Strings) in to Plist.There is No Error.

But When I store this "Array of Objects" It cant be done.

Thanks in Advance.


回答1:


First convert your NSArray to NSDictionary as given here.

Then use NSDictionary's writeToFile:atomically: to store that as Plist.

For this, your class must be conform to NSCoding protocol.

Or otherwise, you can write your NSArray itself directly to plist without converting to NSDictionary. But anyhow, the class should conform to NSCoding protocol.




回答2:


Indicate the .plist path to the class variable correctly

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




回答3:


You cant save objects to Plists. It wont ever work, you would only ever be able to save internal variables to a plist. It you want to save objects, you need to first make your class NSCoding compliant. 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. 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. Then you need to use NSKeyedArchiver to save them. I wrote a nice manager class that will take care of all of this for you as long as your objects ar NSCoding compliant. its available right here https://github.com/caranicas/Save-Manager enjoy!



来源:https://stackoverflow.com/questions/7670586/how-can-i-save-array-of-class-objects-in-to-a-plistiphone-development

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!