0

I am trying to save an array using NSUserDefaults() so that I can access the data even after closing the program. I Have always managed to use it successfully in the past saving Ints and Strings. However when I try to save an array it doesn't work. Here is an example:

 var superarray = [AnyObject?]()
    superarray.append("Test")
    superarray.append(3)
    superarray.append(NSDate()) //random examples

NSUserDefaults.standardUserDefaults().setObject(superarray, forKey: "AnyKey")

It gives the error: "Cannot convert value of type '[AnyObject?]' to expected argument type 'AnyObject?' "

Does this mean that .setObject() cannot take arrays? Is there another alternative?

Thanks in advance!

1 Answer 1

1

NSUserDefaults can only store object with property list type.

Reminder, plist are limited to these objects:

  • NSData
  • NSString
  • NSNumber
  • NSDate
  • NSArray
  • NSDictionary

Se here you could use NSMutableArray instead of your mutable Array

let superarray = NSMutableArray();
superarray.addObject("Test")
superarray.addObject(3)
superarray.addObject(NSDate())

NSUserDefaults.standardUserDefaults().setObject(superarray, forKey: "AnyKey")

More details here: http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.