简体   繁体   中英

NSArray or NSDictionary for storing in UserDefaults?

I've a collection of a usertype News currently stored in a NSArray. I have to store them in UserDefaults to save them on the Device. A News have a property ID which is unique. Before storing them to UserDefaults, I convert the NSArray to a NSDictionary where the key is the ID and the object for this key is the News. Is this a good way to store them?

The reason for choosing an NSDictionary is to be able to check if a News with a specific ID exists in the list of News each time I redownload the News from a Web Service. This way I have only one News instance for each News ID. I think this would be hard to manage using a normal NSArray -- or I'm missing something?

I have to store them in UserDefaults to save them on the Device.

UserDefaults are for storing preferences, settings and other "small" bit of information, they are not for storing application data. You do not "have" to use NSUserDefaults, there are many other options available to you. Writing to files (in the document directory) in their original form or using NSKeyedArchiver/NSKeyedUnarchiver for example.

You can get the document directory path like this

NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

Apart from that storing an NSDictionary with News ids as keys is fine. I don't really see the point of having an NSArray and "converting" it to an NSDictionary, use one or the other (that way you always ensure that you only have one News per item).

NSUserDefaults is not a database, but you already knew it.

Anyway, I'd store the array directly and also save the last seen news ID as a separate preference . Then, you only need to process news items with ID greater than the last seen item. When you download news items you need to update both the news and the last seen ID. You need to guarantee that IDs are in ascending order.

A different approach, depending on your particular use of news, would be to save two arrays, one with the news items and a different one with the list of news IDs. Use the second array to check if there are fresh news.

Unless you are handling lot of news items (in which case you should use Core Data anyway) you are optimizing something that doesn't need optimization. Reading, sorting, updating and saving back a small array into NSUserDefaults is pretty fast.

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