【问题标题】:Read & Save setting an array in array in swift快速读取和保存在数组中设置数组
【发布时间】: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 = selftableView.dataSource = self 移动到viewWillAppear 而不是viewDidLoad

标签: ios arrays swift


【解决方案1】:

数组的类型是字典数组[[String:String]]而不是字符串数组[String]

var objects = [[String:String]]()

...

if let testArray : AnyObject? = defaults.objectForKey("Mybookmarks") {
    objects = testArray as! [[String:String]]  
}

编辑:

并将 Interface Builder 中的 tableview 实例与 IBOutlet 连接起来。 您使用var tableView: UITableView = UITableView() 创建的实例是一个全新的实例,它与IB 中的不同

【讨论】:

  • 我现在在“cell.textLabel?.text = object["name"]!”这一行收到此错误“找不到接受提供的参数的 'subscript' 的重载”跨度>
  • 我编辑了这篇文章。字典数组保证有效,必须删除var关键字(范围错误)
  • 我刚刚在操场上成功测试了代码。 cellForRowAtIndexPath方法中println(object)的结果是什么?
  • 如果我注释对象行,并添加 println(object) 行。它给了我这个结果:{ name = Apple; url = "apple.de"; }
  • 表格视图实例导致问题,见帖子中的编辑
【解决方案2】:

没关系,我发现这不在 [String:String] 中。这必须在 let 对象中: [字符串:字符串] = self.objects[indexPath.row] 现在它可以工作了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-07
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-08
    • 1970-01-01
    相关资源
    最近更新 更多