AlamoFireObjectMapper无法在对象数组中保存数据响应

时间:2016-10-21 04:33:28

标签: ios json swift get alamofire

我正在使用AlamoFireObjectMapper来尝试并将一些简单的JSON映射到某些类模型。似乎我能够正确检索JSON并打印它,但是当我尝试将我的响应附加到我的类类型的数组时,它不起作用。

示例JSON:     SampleJson

names = [item.name for item in items]
frequency = {name:names.count(name) for name in names}
# Give us {doug: 1, kevin: 2, kim: 1}

for item in items:
    if frequency[item.name] > 1:
        item.valid = False

for item in items:
    print item.name, item.valid

    # The output is the same from above. 

的ViewController:

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"]
   }
}

我不能为我的生活找出为什么我可以打印,但不能存储我的数据。那只是不跟我点击。

2 个答案:

答案 0 :(得分:0)

您可能无法创建Mappable类的对象,以便可以向其追加数据。相反,您可以创建另一个模型类并使用其对象。

class movieModel: NSObject {
    var movieTitle: String?
    var movieID: Int?
    var movieRating: String?
    var movieReleaseDate: String?
    var inTheaters: Bool?
}

现在在resultViewController中创建此类的对象,并使用它来存储电影详细信息。

class resultViewController: UITableViewController {
    let movieArray: [movieModel]? //create array of movieModel object
    .......
      ........
        if let movies = result?.movieResults {
           for item in movies {
              let movie = movieModel()//create object of movieModel
              movie.movieTitle = item.movieTitle
              movie.movieID = item.movieID
              movie.movieRating = item.movieRating
              movie.movieReleaseDate = item.movieReleaseDate
              movie.inTheaters = item.inTheaters

              self.movieArray.append(self.movie)
              print(item.movieTitle)
           }
       }
    ........
}

答案 1 :(得分:0)

请求是异步的。在从服务器收到响应之前,不会执行该块 您的for循环在触发请求后直接执行。附加新对象后运行self.tableView.reloadData(),它应该可以正常工作。