Use Managers to Save and Read Data

suggest change

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.

Swift

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;
            }
        }
    }
}

Objective-C

#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:

  1. 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.
  2. Simply call only one method when you want to access to score or write it.
  3. 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents