Search code examples
iosswiftswift3xcode8anyobject

Exception generated while accessing value from AnyObject


This kind of error is generated

[_SwiftValue objectForKey:]: unrecognized selector sent to instance 0x600000a805a0

When I run the below code

 let obvj = object as AnyObject
 print(obvj)
 let ct = obvj.object(forKey: "currenttime") as! Date

Here value of object is

Optional({
    currenttime = "2016-10-14 11:30:12 +0000";
    endtime = "2016-10-14 14:30:12 +0000";
    success = 1;
})

While this was working fine in Swift 2.2


Solution

  • You stated that the object variable is a dictionary type. I could be wrong, but I believe your syntax for a dictionary object is not correct. A dictionary should take the format: [key 1: value 1, key 2: value 2, key 3: value 3].

    Here is the code I ran successfully in a playground:

    //: Playground
    import Foundation
    
    let object = Optional([
        "currenttime" :  "2016-10-14T11:30:12+00:00",
        "endtime" : "2016-10-14T14:30:12+00:00",
        "success" : 1
    ])
    
    let obvj = object as AnyObject?
    print(obvj) // prints the dictionary object
    let ct = obvj!.object(forKey: "currenttime") as! String
    print(ct) // prints: 2016-10-14T11:30:12+00:00
    
    // https://developer.apple.com/reference/foundation/dateformatter    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
    dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
    
    let date = dateFormatter.date(from: ct)
    print(date?.description) // prints: Optional("2016-10-14 11:30:12+0000")
    

    The object var is initialized as an optional dictionary type.

    The line that you have here: let obvj = object as AnyObject should be let obvj = object as AnyObject?. object should be cast as an optional AnyObject because it started as an optional dictionary type.

    I'm not sure how your string as Date is working. It did not work for me. Maybe you added an extension to Date in your code? In my code above, I used a DateFormatter from the standard library and slightly modified the date string to fit the expected format. I followed the sample from the developer reference "Working With Fixed Format Date Representations" found here:

    https://developer.apple.com/reference/foundation/dateformatter