I am currently using this blog where it uses custom classes used with NSKeyedArchiver. Everything seems correct but I am wondering how to get different instances of "student".
http://keeptheseinmind.blogspot.com/2011/10/nskeyedarchiver-tutorial.html
In this tutorial, new instances of the custom class "students" are created each time when the application is terminated. And I have assumed that there are many of these "students" instances within the NSKeyedArchiver, but I am only able to access to only one of them.
Saving to the disk
- (void)saveDataToDisk {
NSString *path = @"~/Documents/data";
path = [path stringByExpandingTildeInPath];
NSMutableDictionary *rootObject;
rootObject = [NSMutableDictionary dictionary];
[rootObject setValue:student forKey:@"student"];
[NSKeyedArchiver archiveRootObject:rootObject toFile:path];
}
Loading from the disk
- (void)loadDataFromDisk {
NSString *path = @"~/Documents/data";
path = [path stringByExpandingTildeInPath];
NSMutableDictionary *rootObject;
rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if ([rootObject valueForKey:@"student"]) {
student = [rootObject valueForKey:@"student"];
}
}
EDIT:
I am mistaken, the instances each time are overwriting each other, each time the application is being terminated. Interesting...
However, my goal is still to create many instances of "students" within one or multiple NSKeyedArchiver. Any ideas would be greatly appreciated.
You can think of
NSKeyedArchiver
as just a way of saving an object (serializing) to disk. In your case, that object is anNSDictionary
, that has exactly one key,student
(I'm using a JSON-ish notation to show the data structures; hopefully intent is clear):As you've noticed, every time you call
saveDataToDisk
, it is just overwriting that single "student" key. To save more than one student, there's a couple ways you could go about it: your choice will depend on how you want to read the data back.One option is to store an array, instead of an
NSDictionary
:If you take this approach, you'll want to make sure that
saveDataToDisk
has access to anNSArray
of students, and pass that array torootObject setValue:
instead:Alternatively, you could imagine wanting to just add more keys to the dictionary, each one representing a student:
In this case, you would again need to make sure that your save function has access to an array of students, but this time you will loop over that array, and add each one to the rootDictionary with its own key that you construct by (for example) concatenating "student" with the studentId.