Fitzy
Fitzy

Reputation: 1889

How to save objects (save/load a game)

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?

Upvotes: 1

Views: 138

Answers (2)

Ilker Baltaci
Ilker Baltaci

Reputation: 11779

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"];

Upvotes: 1

zrzka
zrzka

Reputation: 21229

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.

Upvotes: 0

Related Questions