Reputation: 361
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.
Upvotes: 1
Views: 2256
Reputation: 149
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!
Upvotes: 1
Reputation: 17478
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.
Upvotes: 4
Reputation: 509
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
Upvotes: 1