我想将用户的过滤器选择保存在 FilterViewController
上。
当 FilterViewController
关闭时,NSKeyedArchiver.archiveRootObject
会存档用户的选择。但是,NSKeyedUnarchiver.unarchiveObject
打开初始默认选择(不是用户的选择)。 如何解决这个问题?
FiltersViewController.swift
override func viewWillAppear(_ animated: Bool) {
if let filterSections = NSKeyedUnarchiver.unarchiveObject(withFile: filterViewModel.filtersFilePath) as? [FilterSection] {
// Retrieves initial default selections, NOT user's selection
filterViewModel.filterSections = filterSections
filtersTableView.reloadData()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Saves what user selects
let isSuccessful = NSKeyedArchiver.archiveRootObject(self.filterViewModel.filterSections, toFile: self.filterViewModel.filtersFilePath)
if (isSuccessful) {
print("Saved filters") // This is printed
} else {
print("Didn't Save filters")
}
}
FilterViewModel.swift
class FilterViewModel: NSObject {
// Contains all filtered sections displayed on table view
var filterSections: [FilterSection] = []
// File Path to saved Filter Sections
var filtersFilePath: String {
let manager = FileManager.default
let url = manager.urls(for: .documentDirectory, in: .userDomainMask).first
print("this is the url path in the documentDirectory \(url)")
return (url!.appendingPathComponent("FilterSelectionData").path)
}
override init() {
super.init()
filterSections = self.getFilterSections()
}
}
CompanyViewController.swift
@objc func filterButtonTapped() {
var filterViewModel: FilterViewModel
if (self.filterViewModel != nil) {
filterViewModel = self.filterViewModel! // This runs
}
else {
self.filterViewModel = FilterViewModel()
filterViewModel = self.filterViewModel!
}
let filtersVC = FiltersViewController(filterViewModel: filterViewModel)
self.navigationController?.pushViewController(filtersVC, animated: true)
}
最佳答案
您正在使用 self.getFilterSections
在 FilterViewModel init
中设置 filterSections
。我认为 self.getFilterSections 是一种返回默认值的方法。对我来说,情况不应该是这样,如果您已经归档了一些值,您应该在这个方法中得到它。
虽然,这本身不应该是问题的原因,但可能是诱发bug的原因。如果可能的话,尝试更改 self.getFilterSections 来返回存档值,否则返回默认值,并检查错误是否仍然存在。
关于swift - NSKeyedUnarchiver.unarchiveObject() 取消归档旧对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48285461/