Since iOS10, i am facing to this issue :
Could not cast value of type '__NSSingleObjectArrayI' to 'NSMutableArray' .
There is my code :
manage.POST( url, parameters: params,
constructingBodyWithBlock: { (data: AFMultipartFormData!) in
//Some stuff here
},
success: { (operation: NSURLSessionDataTask?, responseObject: AnyObject?) in
var array : NSMutableArray!
if AppConfig.sharedInstance().OCR == "2"{
let dictionnary = responseObject as! NSDictionary
array = dictionnary["data"]! as! NSMutableArray
}else{
//!!!!CRASH HERE!!!!!
array = responseObject as! NSMutableArray
}
//Some stuff after
}
When i look for responseObject value, i have this in my console :
Printing description of responseObject:
▿ Optional<AnyObject>
▿ Some : 1 elements
- [0] : Test
How can i extract value "Test" from responseObject ?
Many thanks
The crash happens because you assume that the object you receive is NSMutableArray
, even though the object has been created outside your code.
In this case, an array that your code gets is an instance of an array optimized for handling a single element; that is why the cast is unsuccessful.
When this happens, you can make a mutable copy of the object:
array = (dictionnary["data"]! as! NSArray).mutableCopy() as! NSMutableArray
and
array = (responseObject as! NSArray).mutableCopy() as! NSMutableArray
When we deal with response from web server then we can't sure about objects and types. So it is better to check and use objects as per our need. See for your reference related to your question.
if let dictionnary : NSDictionary = responseObject as? NSDictionary {
if let newArr : NSArray = dictionnary.objectForKey("data") as? NSArray {
yourArray = NSMutableArray(array: newArr)
}
}
By this your app will never crashed as it is pure conditional for your needed objects with checking of types. If your "data" key is array then only it will proceed for your array. Thanks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With