按删除按钮时,函数不删除数组项

时间:2015-08-10 05:11:33

标签: ios swift

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath:    NSIndexPath) {
if editingStyle == .Delete {
        allNotes.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

//这是音符类

var allNotes:[Note] = []
var currentNoteIndex:Int = -1
var noteTable:UITableView?

let kAllNotes:String = "notes"

class Note:NSObject {

var date:String
var note:String


override init() {


    date = NSDate().description
    note = ""


}


func dictionary() -> NSDictionary {
    return ["note":note, "date": date]
}


class func savedNotes() {


    var aDictionary:[NSDictionary] = []
    for var i:Int = 0; i < allNotes.count; i++ {
        aDictionary.append(allNotes[i].dictionary())

    }


    NSUserDefaults.standardUserDefaults().setObject(aDictionary, forKey: kAllNotes)


}

class func loadNotes() {

    var defaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    var savedData:[NSDictionary]? = defaults.objectForKey(kAllNotes) as? [NSDictionary]
    if let data:[NSDictionary] = savedData {
        for var i:Int = 0; i < data.count; i++ {

            var n:Note = Note()
            n.setValuesForKeysWithDictionary(data[i] as [NSObject : AnyObject])
            allNotes.append(n)

        }

    }



}

}

这是函数,但它不会永久删除数组上的项目,从表视图中临时删除。当重新启动模拟器时,仍然表视图显示已删除的项目

 override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {
        allNotes.removeAtIndex(indexPath.row)
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        NSUserDefaults.standardUserDefaults().setObject(allNotes, forKey: kAllNotes)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

当我像这样更新任何尝试删除数组项时,显示一个线程错误

1 个答案:

答案 0 :(得分:0)

是的,它只会在运行时从您的allNotes阵列中删除,因为您没有从内存中删除allNotes数组获取值的位置。

例如,如果您正在从内存中的plist文件中读取数组,那么您也必须从该plist文件中删除该项目。

因此,当您重新启动应用时,allNotes数组将不会从您的plist中获取该已删除的项目。并且它不会显示已删除的项目。