Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AnyObject? does not have a member named 'objectAtIndex'

Got a error on (Xcode6 BETA 6) if a try to get an object of string:

let jsonString : String = "[{\"name\":[\"Fred\",\"John\"],\"age\":21},{\"name\":\"Bob\",\"age\":35}]"

let myData:NSData? = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)

var jsonResult:NSArray = NSJSONSerialization.JSONObjectWithData(myData!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray

println(jsonResult.objectAtIndex(0).objectForKey("name").objectAtIndex(0))

print never get called, cause the error. Anyone a idea?

like image 908
kurtanamo Avatar asked Dec 14 '22 20:12

kurtanamo


2 Answers

Getting value from NSDictionary or NSArray return AnyObject object. So you should type cast to appropriate type. Try this

println(((jsonResult.objectAtIndex(0) as NSDictionary).objectForKey("name") as NSArray).objectAtIndex(0))
like image 179
Yatheesha Avatar answered Dec 28 '22 15:12

Yatheesha


Another option would be to cast jsonResult to an Array<AnyObject> and use subscript syntax to get necessary value

let jsonString : String = "[{\"name\":[\"Fred\",\"John\"],\"age\":21},{\"name\":\"Bob\",\"age\":35}]"
let myData:NSData? = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
var jsonResult: AnyObject = NSJSONSerialization.JSONObjectWithData(myData!, options: NSJSONReadingOptions.MutableContainers, error: nil);

if let lJsonArray = jsonResult as? Array<AnyObject> {
    println(lJsonArray[0].objectForKey("name")[0])
}
like image 36
nsinvocation Avatar answered Dec 28 '22 15:12

nsinvocation