开发者

Advantages of using NSUserDefaults to save game settings/state?

开发者 https://www.devze.com 2023-04-10 03:35 出处:网络
Is there any benefit in going with NSUserDefaults to save game state/settings over creat开发者_JS百科ing a binary file in plain C?

Is there any benefit in going with NSUserDefaults to save game state/settings over creat开发者_JS百科ing 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 (e.g. 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, i.e. 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 (e.g. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消