While you can use the NSUserDefaults
methods anywhere, it can sometimes be better to define a manager that saves and reads from NSUserDefaults
for you and then use that manager for reading or writing your data.
Suppose that we want to save a user’s score into NSUserDefaults
. We can create a class like the one below that has at two methods: setHighScore
and highScore
. Anywhere you want to access the high scores, create an instance of this class.
public class ScoreManager: NSObject {
let highScoreDefaultKey = "HighScoreDefaultKey"
var highScore = {
set {
// This method includes your implementation for saving the high score
// You can use NSUserDefaults or any other data store like CoreData or
// SQLite etc.
NSUserDefaults.standardUserDefaults().setInteger(newValue, forKey: highScoreDefaultKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
get {
//This method includes your implementation for reading the high score
let score = NSUserDefaults.standardUserDefaults().objectForKey(highScoreDefaultKey)
if (score != nil) {
return score.integerValue;
} else {
//No high score available, so return -1
return -1;
}
}
}
}
#import "ScoreManager.h"
#define HIGHSCRORE_KEY @"highScore"
@implementation ScoreManager
- (void)setHighScore:(NSUInteger) highScore {
// This method includes your implementation for saving the high score
// You can use NSUserDefaults or any other data store like CoreData or
// SQLite etc.
[[NSUserDefaults standardUserDefaults] setInteger:highScore forKey:HIGHSCRORE_KEY];
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSInteger)highScore
{
//This method includes your implementation for reading the high score
NSNumber *highScore = [[NSUserDefaults standardUserDefaults] objectForKey:HIGHSCRORE_KEY];
if (highScore) {
return highScore.integerValue;
}else
{
//No high score available, so return -1
return -1;
}
}
@end
The advantages are that:
The implementation of your read and write process is only in one place and you can change it (for example switch from NSUserDefaults
to Core Data) whenever you want and not worry about changing all places that you are working with the high score.
Simply call only one method when you want to access to score or write it.
Simply debug it when you see a bug or something like this.
Note
If you are worried about synchronization, it is better to use a singleton class that manages the synchronization.