NSKeyedUnarchiver.unarchiveObject()取消归档旧对象

时间:2018-01-16 16:10:24

标签: swift swift3 nsfilemanager nskeyedarchiver nskeyedunarchiver

我想在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)

    }

1 个答案:

答案 0 :(得分:0)

您正在使用self.getFilterSectionsfilterSections中设置FilterViewModel init。我想self.getFilterSections是一个返回默认值的方法。对我来说,情况应该不是这样,相反,如果你已经存档了一些值,你应该用这种方法得到它。

虽然,这不应该是问题的原因,但可能是诱发bug的原因。尝试更改self.getFilterSections以返回归档值(如果可能),否则返回默认值并检查错误是否仍然存在。