Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not cast value of type NSSingleObjectArray to NSMutableArray

Tags:

ios10

swift

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

like image 930
Kevin ABRIOUX Avatar asked Sep 27 '16 11:09

Kevin ABRIOUX


2 Answers

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
like image 147
Sergey Kalinichenko Avatar answered Nov 01 '22 23:11

Sergey Kalinichenko


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.

like image 8
Max Avatar answered Nov 02 '22 01:11

Max