PDA

View Full Version : saving variables to a file




liptonlover
Sep 24, 2008, 05:29 PM
I will not have actual whole objects to save, just particular variables. They will be ints, floats and doubles. How do I do this?



robbieduncan
Sep 24, 2008, 05:30 PM
Easiest way is to stick them in a NSDictionary (wrapped in NSValue/NSNumber objects if required) and save that via the obvious method.

liptonlover
Sep 24, 2008, 05:51 PM
hmm.... looking at the class doc it seems I'll have to wrap them in an NSNumber or NSValue, then an NSArray, THEN an NSDictionary. Seems like that's taking the long way... and it doesn't help that I haven't used NSDictionary or successfully saved an object or variable before. I'll look into it more but I'd like more suggestions please.

robbieduncan
Sep 24, 2008, 05:54 PM
I've no idea what you're using the array for. Create an NSMutableDictionary instance. Set each value you want to save for a sensible key. Write out via the writeToFile: method. No array...

liptonlover
Sep 24, 2008, 06:07 PM
Sorry I was looking at NSDictionary, not Mutable. Thanks!

firewood
Sep 24, 2008, 07:08 PM
When I don't care about tiny rounding errors, I just convert to string representation (sprintf), and write plain text files. Makes it much easier to dump the file to a text editor for debugging or printing, or for moving the data cross-platform.

robbieduncan
Sep 25, 2008, 04:57 AM
When I don't care about tiny rounding errors, I just convert to string representation (sprintf), and write plain text files. Makes it much easier to dump the file to a text editor for debugging or printing, or for moving the data cross-platform.

Whilst this approach is perfectly sensible it does take more code, especially to reload. We can reload the dictionary from a file with one line of code :D