I would like to have a “permanent” NSDictionary in my app, in which from the beginning of the app launch, I can get access to the elements and even after I kill the app and start it again.
This NSDictionary needs to be stored tightly with the app. One way would be to just to create the NSDictionary from a Web Service data every time the app launches, then create a singleton class that would represent this NSDictionary, but I don’t think this is good.
The NSDictionary will approximately hold 10-20 objects, where the key would be a NSString or NSDate and the value would be a NSArray. The NSArray would have a maximum of approximately 50 entries in it (on average probably there will only be 5-25 entries).
I am planning to use this NSDictionary as a part of a calculation that I am doing inside the delegate locationManager:didUpdateToLocation:fromLocation: each time a user moves every 50-100 meters.
Suggestions are appreciated on the best way I could do this.
Just having the NSDictionary in a singleton will not keep it between app launches, you’ll need to save it to disk, and then read it from the disk when the app starts.
If you have no custom objects (subclasses you’ve created) in the NSDictionary, or in the NSArrays or non at all, you can use this method to save the NSDictionary is:
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flagand to open the dictionary from disk:
- (id)initWithContentsOfFile:(NSString *)pathHowever if you do have custom objects they will need to conform to the NSCoding protocol. And you’ll have to use 2 different methods to save and open it:
NSCoding is a protocol, so in your header you need to add it on the end of the interface line:
(where the only thing you should add is
<NSCoding>)Then in your implementation of your subclass, you need to add the following methods:
- (id)initWithCoder:(NSCoder *)decoderand:
- (void)encodeWithCoder:(NSCoder *)encoderThe
initWithCoder:method gets called when you want to unarchive(/open) your NSDictionary (which somewhere contains this class)encodeWithCoder:is what gets called when your NSDictionary is archived(/saved).You don’t call either of these yourself. You need to add code in them:
You need to have similar lines for each value you want to store (generally all the properties, [and instance variables] your class has). Note the how the
floatline is different to the others.The keys can be any string you want, as long each property has it’s own unique key and that they match between the two methods. I personally use the name of the property as it’s just easier to understand.
when you actually want to save your NSDictionary you use:
and to open the dictionary:
(depending on your code you may need to
retainmyDictionary)To get the path to your dictionary (for both saving and opening) do:
Hope that helps, if you have any more questions about this answer, just comment 🙂