2
self.fetchMin(forStartDate: start, toEndDate: end) { (min, chal) in

    guard let mins = min, let challenges = chal else {
        return
    }

    let dict: [Int : [String]]  = [mins:challenges]

    UserDefaults.standard.set(dict, forKey: "WeekStates")

}

Hi, In the above program I'm trying to store key and array pair of string in userDefaults but if I do so it crashes unexpectedly.

If I try with one value, its working.

eg:

`let dict: [String]  =  challenges
 UserDefaults.standard.set(dict, forKey: "WeekStates")
5
  • whats the crash u faced Commented Jun 16, 2017 at 4:58
  • libc++abi.dylib: terminating with uncaught exception of type NSException @Anbu.Karthik Commented Jun 16, 2017 at 5:03
  • its the NSException can you show the full crash report Commented Jun 16, 2017 at 5:04
  • can I send it to your mailID? @Anbu.Karthik Commented Jun 16, 2017 at 5:12
  • There will be a "Reason" mentioned in console after "terminating with uncaught exception of type NSException". SHare that please. Commented Jun 16, 2017 at 5:36

2 Answers 2

2

https://developer.apple.com/documentation/foundation/userdefaults

The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object must be a property list—that is, an instance of (or for collections, a combination of instances of): NSData , NSString , NSNumber , NSDate , NSArray , or NSDictionary . If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see Preferences and Settings Programming Guide.

You can do something like this.

let dict: [Int : [String]]  = [1:["iOS Dev"]]

    UserDefaults.standard.set(NSKeyedArchiver.archivedData(withRootObject: dict as NSDictionary) as NSData, forKey: "4WeekStates")

    if let unarchivedObject = UserDefaults.standard.object(forKey: "4WeekStates") as? Data {

        let dic = NSKeyedUnarchiver.unarchiveObject(with: unarchivedObject as Data) as? NSDictionary
        print(dic!)
    }
Sign up to request clarification or add additional context in comments.

Comments

0

As you mentioned at last point i tried [String] it works.

I'm not sure whether you can store data like type of [Int : [String]], As of my knowledge UserDefaults Property lists can only accept certain types of variables, so it has that limitation. You can store these types of variables:

  1. Array
  2. Data
  3. Date
  4. Dictionary
  5. NSNumber
  6. String

2 Comments

I am saving it has a dictionary only.
you cannot store dictionary with a NSNumber or Int as key

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.