Mike Chen
Mike Chen

Reputation: 2608

Saving a list each time it changes

I'm writing an application where a user can add and remove objects from several lists. In order to save their lists even when the application crashes, I want to write them to the disk every time they change. My current plan is to create a class that observes the lists and thus is notified each time one changes, in order to archive them (the lists and all objects in them follow the NSCoding protocol).

It should be noted that I know in advance how many lists there will be, and that these lists are not expected to grow to more than 100 items in length (most will be 10-20).

Is this the best way to achieve what I want to achieve? Should this even be a problem I am worried about, or is it acceptable to only create mementos of these lists when the application exits? I was also considering subclassing NSMutableArray to make a class that saves itself whenever it changes, so that no one class must be aware of all lists that should be saved.

Upvotes: 1

Views: 70

Answers (1)

Rob Napier
Rob Napier

Reputation: 299355

First, good instinct here to worry about the user's data. Yes, of course you should fix your crashes. But even so, you should be protective of the user's data first and foremost. Secondly you should be worried about the user's battery life. So you shouldn't hit their flash drive too often.

If the number of changes aren't large, then I'd recommend creating "list" objects that has-a NSMutableArray (rather than is-a NSMutableArray). You can just write yourself to disk anytime someone calls addItem: in order to always be in sync. If changes happen very quickly, it's pretty easy to build trampolines that will save "every second if there has been a change, but no more often than once a second." (If this is any problem, add a comment and I'll post some code or blog it; it's not difficult.)

Upvotes: 2

Related Questions