[英]initialize array of dictionaries for a json file in Swift
I just started using Swift
and I would like to display the result of parsing a JSON
file in a UITableView
. 我刚刚开始使用
Swift
,我想在UITableView
显示解析JSON
文件的结果。 The problem comes from the initialization of my NSMutableArray
news which will contain all the objects to display. 问题来自我的
NSMutableArray
新闻的初始化,该新闻将包含要显示的所有对象。
I have the Error : 我有错误:
error : "/Users/******/Documents/developper/******/*******
/NewsTableViewController.swift:79:22: 'NSMutableArray?'
does not have a member named 'count'
Code is : 代码是:
import UIKit
class NewsTableViewController: UITableViewController {
var bytes: NSMutableData?
// var news: NSArray = []
var news: NSMutableArray?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
// this is our remote end point (similar to URLRequest in AS3)
let request = NSURLRequest(URL: NSURL(string: "http://mangerdulion.com/wp-content/newsInnoven.json")!)
// this is what creates the connection and dispatches the varios events to track progression, etc.
let loader = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.bytes?.appendData(conData)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.bytes = NSMutableData()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
// we serialize our bytes back to the original JSON structure
let jsonResult: Dictionary = NSJSONSerialization.JSONObjectWithData(self.bytes!, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
// we grab the colorsArray element
let results: NSArray = jsonResult["newsArray"] as NSArray
self.news?.addObjectsFromArray(results)
/*
// we iterate over each element of the colorsArray array
for item in results {
// we convert each key to a String
var titre: String = item["titreNews"] as String
var date: String = item["dateNews"] as String
var contenu: String = item["contenuNews"] as String
println("\(titre): \(date):\(contenu)")
}
*/
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
//println(self.news?.count)
return self.news.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
let titre: NSDictionary = self.news[indexPath.row] as NSDictionary
cell.textLabel?.text = titre["titreNews"] as? String
println(cell.textLabel?.text)
// Get the formatted price string for display in the subtitle
let contenu: NSString = titre["contenuNews"] as NSString
cell.detailTextLabel?.text = contenu
return cell
}
Create a mutable array at the top of your class, and don't put any "?" 在类的顶部创建一个可变数组,不要添加任何“?” or "!"
要么 ”!” after news.
新闻之后。
var news: NSMutableArray = []
You also need to call reloadData on your table view at the end of the connectionDidFinishLoading method 您还需要在connectionDidFinishLoading方法的末尾在表视图上调用reloadData
Putting ?
放
?
character at the end of your class while declaring a variable creates an Optional
variable. 在类的末尾声明一个变量时,该字符会创建一个
Optional
变量。 Optional
variables can be nil or have a value Optional(value). Optional
变量可以为nil或具有值Optional(value)。 You have to unwrap the Optional to use it. 您必须打开Optional才能使用它。
var news:NSMutableArray?
creates an optional
array. 创建一个
optional
数组。
items?.count
will also return an optional Optional(Int). items?.count
也将返回可选的Optional(Int)。 This cannot be returned in the UITableView
count method. 无法在
UITableView
count方法中返回该值。
I don't think you need to use an optional here. 我认为您无需在此处使用可选选项。 Instead you can use an empty array for convenience.
相反,您可以使用一个空数组以方便使用。
var news: NSMutableArray = []
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.