简体   繁体   中英

Retrieving and casting data from an array in Parse and SWIFT

This error always show when I try to retrieve and append the elements of an array in Parse to an array created in the code:

Could not cast value of type '__NSArrayM' (0x10b281b60) to 'NSString' (0x10bdc5b48).

However, when I use print, it works with no errors and I can get the data

 var query = PFQuery(className: "Courses")

 query.whereKey("subject", equalTo: "\((object["course"] as! String))")                        
 query.findObjectsInBackgroundWithBlock { (objects, error) in

 if let objects = objects
 {
     for object in objects
     {                       
         print(object["subject"] as! String)
         self.courses.append(object["subject"] as! String)
         print(object.valueForKey("timeToShow")!)  
         // it works to print the elemnts in array from parse self.dates.append((object.valueForKey("timeToShow") as! String))  
         // this line shows the error down !

         self.tableView.reloadData()
     }
}

图片更多细节

From what you said:

  1. self.dates is an array of type String
  2. object.valueForKey("timeToShow") is an array of type String
  3. You want to append the values in object.valueForKey("timeToShow") to the end of self.dates

So instead of casting to a String and trying to append, you need to append all of the values of the array (note this depends on the version of Swift that you are using):

let times = object.valueForKey("timeToShow") as! [String]
self.dates += times 

// Or:
self.dates.extend(times) // Swift 1.2
self.dates.appendContentsOf(btimes) // Swift 2
self.dates.append(contentsOf: times) // Swift 3

Appending an array to another array taken from this StackOverflow example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM