使用tableView滑动功能从NSUserDefaults中删除项目时出错

时间:2015-01-29 10:23:20

标签: ios uitableview swift nsuserdefaults

我尝试使用tableView滑动功能从NSUserDefaults中删除项目。但是当我测试我的应用程序时,它总是在点击“删除”后崩溃。

定义变量并从NSUserDefaults加载数据:

 var exercises:NSMutableArray = NSMutableArray();

...

override func viewDidLoad() {
    super.viewDidLoad()

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var exercisesListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray

    if ((exercisesListFromUserDefaults) != nil){
        exercises = exercisesListFromUserDefaults!
    }
    self.tableView.reloadData()

}

删除功能:

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if editingStyle == .Delete {

        self.deleteItem(exercises[indexPath.row])

        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
}

func deleteItem(sender: AnyObject) {
    exercises.removeObject(sender)

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject(exercises, forKey: "exercisesList")
    userDefaults.synchronize()
}

编辑: 错误:

(lldb)bt * thread#1:tid = 0x190c34,0x0000000108715282 libsystem_kernel.dylib __pthread_kill + 10, queue = 'com.apple.main-thread', stop reason = signal SIGABRT frame #0: 0x0000000108715282 libsystem_kernel.dylib __ pthread_kill + 10     帧#1:0x00000001087484c3 libsystem_pthread.dylib pthread_kill + 90 frame #2: 0x00000001084a519a libsystem_sim_c.dylib abort + 129     第3帧:0x0000000108759481 libc ++ abi.dylib abort_message + 257 frame #4: 0x00000001087813d5 libc++abi.dylib default_terminate_handler()+ 267     帧#5:0x0000000107c1de19 libobjc.A.dylib _objc_terminate() + 103 frame #6: 0x000000010877eb01 libc++abi.dylib std :: __ terminate(void(*)())+ 8     第7帧:0x000000010877e7aa libc ++ abi.dylib __cxa_rethrow + 99 frame #8: 0x0000000107c1dd2c libobjc.A.dylib objc_exception_rethrow + 40     第9帧:0x000000010600453e CoreFoundation CFRunLoopRunSpecific + 654 frame #10: 0x000000010a1d09f0 GraphicsServices GSEventRunModal + 161     帧#11:0x0000000106965420 UIKit UIApplicationMain + 1282 * frame #12: 0x0000000105ee2c5e Progress top_level_code + 78 at AppDelegate.swift:12     帧#13:0x0000000105ee2c9a进度main + 42 at AppDelegate.swift:0 frame #14: 0x00000001083f7145 libdyld.dylib开始+ 1

1 个答案:

答案 0 :(得分:2)

这一行

var exercisesListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray

是一个问题,因为数组不可变。用户默认值始终返回不可变对象。您需要先创建此数组的可变数组(副本),然后才能更改它并将其存储回用户默认值。

var myMutableArray = NSMutableArray(array: myImmutableArray)