保持对下载的DynamoDB数据的引用

时间:2018-03-25 22:32:20

标签: swift amazon-web-services amazon-dynamodb

我有一个持有DynamoDB模型的类(我为了简洁而剪切了变量#,但它们都是可选字符串:

import AWSCore
import AWSDynamoDB

@objcMembers class Article: AWSDynamoDBObjectModel, AWSDynamoDBModeling {

  var _articleSource: String?

  class func dynamoDBTableName() -> String {
    return "article"
  }

  class func hashKeyAttribute() -> String {
    return "_articleId"
  }

  class func rangeKeyAttribute() -> String {
    return "_articleUrl"
  }

  override class func jsonKeyPathsByPropertyKey() -> [AnyHashable: Any] {
    return [
      "_articleSource" : "articles.articleSource",          
    ]
  }
}

在我的View Controller中,我从表中下载数据并将每篇文章存储在这样的数组中:

let dynamoDbObjectMapper = AWSDynamoDBObjectMapper.default()
var allArticles = [AnyObject]()

func getArticles(completed: @escaping DownloadComplete) {
  let scanExpression = AWSDynamoDBScanExpression()
  scanExpression.limit = 50
  self.dynamoDbObjectMapper.scan(Article.self, expression: scanExpression).continueWith(block: { (task:AWSTask<AWSDynamoDBPaginatedOutput>!) -> Any? in
  if let error = task.error as NSError? {
    print("The request failed. Error: \(error)")
  } else if let paginatedOutput = task.result {
    for article in paginatedOutput.items as! [Article] {
      self.allArticles.append(article)
    }
  }
  return(self.allArticles)
  })
  completed()
}

当我尝试使用应存储在allArticles中的数据时,数组为空。但是,当我在附加文章的下载块中中断执行时,该数组会保留文章。如何保存对下载数据的引用?我使用完成块是我的尝试。

编辑:allArticles的类型为[AnyObject],因为我试图在同一个数组中存储来自3个不同类的对象,以便更容易在TableView中使用

1 个答案:

答案 0 :(得分:0)

阵列毕竟不是空的,我只是没有意识到这一切都是异步的(呃...)

我只是需要:

DispatchQueue.main.async {
    self.tableView.reloadData()
  }

代替completed() func

中的getArticles()