我正在使用AlamoFireObjectMapper尝试并将一些简单的JSON映射到某些类模型。看来,我能够正确地检索JSON并将其打印出来,但是当我尝试将我的响应追加到我的类类型的数组时,它不起作用。AlamoFireObjectMapper无法在对象数组中保存数据响应
class MovieResults: Mappable {
var movieResults: [MovieInfo]?
required init?(map: Map) {
mapping(map: map)
}
func mapping(map: Map) {
// An array of objects
self.movieResults <- map["results"]
}
}
class MovieInfo: Mappable {
var movieTitle: String?
var movieID: Int?
var movieRating: String?
var movieReleaseDate: String?
var inTheaters: Bool?
var movieResults: [MovieInfo]?
required init?(map: Map) {
}
func mapping(map: Map) {
self.movieTitle <- map["title"]
self.movieID <- map["id"]
self.movieRating <- map["rating"]
self.movieReleaseDate <- map["release_date"]
self.inTheaters <- map["in_theaters"]
}
}
的ViewController:
class resultViewController: UITableViewController {
var searchTerm: String?
var movieArray = [MovieInfo]()
override func viewDidLoad() {
super.viewDidLoad()
fetchAPI(search: searchTerm!)
}
func fetchAPI(search: String) {
let gboxAPI = "rK5M0dCTUd268hk121BpNpEAxMOmFuNh"
let URL = "http://api-public.guidebox.com/v1.43/US/\(gboxAPI)/search/movie/title/\(searchTerm!)/fuzzy"
Alamofire.request(URL).responseObject { (response: DataResponse<MovieResults>) in
let result = response.result.value
if let movies = result?.movieResults {
for item in movies {
self.movieArray.append(item) //this doesn't work
print(item.movieTitle) //this works
}
}
}
/* This doesn't print anything
for some reason my array isn't truly being
popluated in the above fetchAPI call
*/
for item in movieArray {
print(item.movieTitle)
}
}
override func tableView(_ tablView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return movieArray.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .value1, reuseIdentifier: "UITableViewCell")
let movieItem = movieArray[indexPath.row]
cell.textLabel?.text = movieItem.movieTitle
cell.detailTextLabel?.text = movieItem.movieRating
return cell
}
}
我不能为我的生命弄清楚为什么我可以打印,但不能储存我的数据。那只是不点击我。
let movieArray:[movieModel]?不会创建一个数组,这会使movieModel的属性,[movieModel]也没有成员'追加',即使这样做不起作用,因为它是用'let'定义的常量。感谢您的帮助,我会继续搜索。 – Wrenzoe