I am currently looking for a way to save objects within an Iphone app I am developing. As this game involves clearing 'levels,' I want to be able to store an array somewhere to indicate which levels have been completed. However, this must be independent of the game, as quitting the game must not cause the data to be lost. How do I go about doing this?
Asked
Active
Viewed 136 times
1
-
Check the link. Hope it will help you ) http://stackoverflow.com/questions/2206013/save-and-load-data-iphone-sdk – Dream.In.Code Oct 14 '12 at 10:00
2 Answers
1
Easiest way to save an restore objects is NsUserdefaults.
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
[prefs synchronize];
For retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];
For other types of objects
[prefs objectForKey:@"anyObjectKey"];

Ilker Baltaci
- 11,644
- 6
- 63
- 79
-
-
do not forget the [prefs synchronize]; after writing to user defaults. Othwerwise you will not have them saved. – Ilker Baltaci Oct 14 '12 at 10:04
-
-
1Usually there is no need to call `synchronize` manually. See the discussion to [`synchronize`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html#//apple_ref/doc/uid/20000318-CIHDDEGI) "Because this method is automatically invoked at periodic intervals, use this method only if you cannot wait for the automatic synchronization (for example, if your application is about to exit) or if you want to update the user defaults to what is on disk even though you have not made any changes." – Matthias Bauch Oct 14 '12 at 10:11
0
Small chunk of data
Go with NSUserDefaults
. Also you can sync NSUserDefaults
to iCloud with https://github.com/MugunthKumar/MKiCloudSync for example. Thus progress is saved even when user deletes and installs your app again, ...
Big chunk of data
Use CoreData
with sqlite
for example.

zrzka
- 20,249
- 5
- 47
- 73
-
Thanks alot, `NSUserDefaults` looks very appropriate for a small task like this! :) – Fitzy Oct 14 '12 at 10:01