1

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?

Fitzy
  • 1,871
  • 6
  • 23
  • 40

2 Answers2

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
  • Very helpful, I will definitely try this. Thank you! – Fitzy Oct 14 '12 at 10:02
  • 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
  • I'll make sure to remember that. – Fitzy Oct 14 '12 at 10:05
  • 1
    Usually 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