1
我是新來的iOS開發我試圖在swift中顯示數據在tableview中的數據來自webservice爲我使用NSURLSessionDataTask。數據如下所示:如何將字典值從字典數組中存儲到數組中
{ categorys: [
{
category_id: "all",
category_name: "ALL",
category_desc: "All Categories"
},
{
category_id: "1",
category_name: "Art",
category_desc: "Artffsdfsdfds "
},
{
category_id: "4",
category_name: "Education",
category_desc: "Education for children and adults"
}]
}
我想在tableview中顯示「category_name」名稱。 下面是我試過的代碼,並試圖在tableview中顯示名稱。
import UIKit
class ViewController: UIViewController, UITableViewDelegate
{
@IBOutlet var dataTableView: UITableView!
var items: NSArray = []
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//table
self.dataTableView!.delegate = self
self.dataTableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.dataTableView)
getData({data, error -> Void in
if (data != nil)
{
self.items = NSMutableArray(array: data)
self.dataTableView!.reloadData()
}
else
{
println("api.getData failed")
println(error)
}
})
}
func getData(completionHandler: ((NSArray!, NSError!) -> Void)!) -> Void
{
let url = NSURL(string: "http://sample.com/srd/games/category")!
var request: NSURLRequest = NSURLRequest(URL:url)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
if (error != nil)
{
return completionHandler(nil, error)
}
var error: NSError?
let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
let names = json["categorys"] as NSArray
println(names)
})
task.resume()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
{
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
cell.textLabel.text = self.items[indexPath.row]["categorys"] as? NSString
return cell
}
}
感謝您的回答JNY,在上面我能夠得到意思是「categorys」數組的字典數組。我無法檢索「category_name」。不幸的是你的代碼也不適合我。當我把你的代碼並運行它崩潰。 – svs 2014-11-21 04:12:32
打印您的dic_categorys!和哪行代碼崩潰? – JNYJ 2014-11-21 05:54:28
在這條線我得到崩潰「var array_item:NSArray!= dic_categorys.valueForKey(」categorys「)作爲NSArray」。錯誤是致命錯誤:在解包可選值時意外發現爲零 array_item的打印說明:陣列的 印刷描述: (NSArray的)陣列= 0x000000010f489c13 { ObjectiveC.NSObject = { } } –
svs
2014-11-21 07:46:15