简体   繁体   中英

Advantages of using NSUserDefaults to save game settings/state?

Is there any benefit in going with NSUserDefaults to save game state/settings over creating a binary file in plain C?

Specifically for an iOS game.

The biggest advantage with NSUserDefaults is that you don't have to worry about the actual writing to "disk" — -synchronize is automatically called at "appropriate times", which includes app background (if multitasking is supported) or termination (if multitasking is not supported, or you set UIApplicationExitsOnSuspend or whatever it's called). This means you can update NSUserDefaults much more frequently without as much overhead.

The disadvantage is that I'm pretty sure the whole thing is loaded into memory and a write involves writing the whole file (I think it even writes to a temporary file and then does a rename), so it's not suitable for storing large, infrequently-changing blobs (eg photos).

Unless your saved games are huge, I'd do something reasinably simple with NSUserDefaults, mostly because it avoids you having to keep track of a bunch of files.

EDIT: A potentially major drawback with NSUserDefaults is that doesn't save when the app crashes, so you might still want to explicitly -synchronize occasionally, depending on how crashy your app is. This is particularly noticable for developers, since pressing "stop" in Xcode (or unplugging the phone while debugging) is effectively a crash!

NSUserDefaults is the appropriate location for settings, but probably not save games.

The advantage is you get in-memory caching and several decades of stability behind it. The downside is you are fairly limited in what you can put in a user defaults file (objects must be plist -friendly, ie strings, numbers, data, dates, dictionaries, and arrays only.) As well, saving game state in NSUserDefaults would make it more difficult to handle multiple save games.

I would recommend you build your logic classes such that they can be serialized/deserialized to/from an arbitrary byte stream (easiest way to do that is to implement NSCoding on your various game state classes.) Then you can just dump files to disk to arbitrary locations (eg a "quicksave" copy in NSUserDefaults and a list of full savegames in [yourapp]/Documents/ . The task of encoding/decoding is not actually strongly associated with the task of storage/retrieval, as surprising as that might be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM