SteMa SteMa - 8 months ago 24
Swift Question

NSUserDefaults returns NSDictionary instead of NSArray

This is how I store the NSArray:

let defaults = NSUserDefaults.standardUserDefaults()
for item in data as NSArray {
if let id = item["id"] as? String {
defaults.setObject(item, forKey: "Content:" + id);

But when I try to get the stored data, I had to use

if let content = defaults.dictionaryForKey("Content:" + contentID) {}

Otherwise the content is empty. But that would be ok if there would be an simple method to get this NSDictionary into an NSArray (as it is needed in some other classes, to which the data is handed over).

Is there something wrong by the way I store the NSArray? BTW: its an array where the keys are Strings. Something like String:AnyObject.

Thanks in advance!



I think your objects are set just fine in user defaults, but you are saving dictionaries in user defaults (because your item is a dictionary), this is why you must use defaults.dictionaryForKey. You could store the whole array using

defaults.setObject(data as NSArray, forKey: "Some key");