我必须将数据放入 TableView 中,但即使我从 JSON 获取信息,我也无法将数据传递给 postTitle 变量。这是为什么?这是我的代码:
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var postTitle = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
var baseURL = "https://hacker-news.firebaseio.com/v0/topstories.json"
// https://hacker-news.firebaseio.com/v0/item/9324191.json
if let url = NSURL(string: baseURL) {
var taskURL = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
println("Error: \(error.localizedDescription)")
} else {
var jsonError: NSError?
if let topStories = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &jsonError) as? NSArray {
self.postTitle.append(topStories)
}
}
})
taskURL.resume()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println(postTitle.count)
return postTitle.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
println(self.postTitle)
// cell.textLabel?.text = postTitle[indexPath.row]
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
topStories
是一个 NSArray
,但您要将其附加到 postTitle
数组(其类型为 [AnyObject]
)。 Array.append
将单个项目添加到数组中。因此,您将在 postTitle
数组中添加一个条目,即一组帖子 ID 的 NSArray
。
我猜你想要的是将 topStories
的内容添加到 postTitle
中?在这种情况下,您希望使用 extend
而不是 append
方法:
self.postTitle.extend(topStories)
关于arrays - 如何在 Swift 中将数据从 NSArray 传输到 String?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29461926/