【发布时间】:2015-07-03 22:16:14
【问题描述】:
我尝试从我的保存设置“Mybookmarks”中加载此数组,并尝试将其写入表格中。那是在设置中=>
[["name" : "apple", "url": "http://www.apple.de"],
["name" : "youtube", "url": "http://www.youtube.de"]]
但它不起作用,它说总是崩溃。我想加载这种数组并将其写入 tableview。 关于如何解决这个问题的任何想法,以便它可以从我的“var defaults = NSUserDefaults.standardUserDefaults()”中读取。
// ViewController.swift
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource {
// create references to the items on the storyboard
// so that we can animate their properties
var tableView: UITableView = UITableView()
var objects = []
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
//read
if let testArray : AnyObject? = defaults.objectForKey("Mybookmarks") {
var objects : [NSString] = testArray! as! [NSString]
println("\(testArray)")
}
tableView.frame = CGRectMake(0, 0, 300, view.frame.height);
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.objects.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier("cell") as! UITableViewCell
let object = self.objects[indexPath.row]
cell.textLabel?.text = object["name"]!
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
println("You selected cell #\(indexPath.row)!")
}
}
【问题讨论】:
-
如果
println("\(testArray)")打印的值正确,请尝试将tableView.delegate = self和tableView.dataSource = self移动到viewWillAppear而不是viewDidLoad