|
顾名思义,备忘录模式用来保存当前程序退出时,当前上下文的文档的数据;在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先的保存状态。当满足以下两个条件时需要考虑使用这一模式: - 需要保存一个对象在某一时刻的状态,这样以后就可以恢复到先前的状态;
- 用于获取状态的接口会暴露细节,需要将其隐藏起来。
在本例中,我在cell的点击事件添加了删除绘本事件,用来删除被点击的书籍,具体代码如下: func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let alertVc = UIAlertController(title: "要删除这本绘本么", message: "", preferredStyle: .alert) let sureAction = UIAlertAction(title: "确定删除", style: .default, handler: { (_) in BookAPI.sharedInstance.deleteBookAt(index: indexPath.item) // 发送删除绘本的请求 self.books = BookAPI.sharedInstance.getBooks() // 更新数据源 self.bookView?.deleteItems(at: [indexPath]) BookAPI.sharedInstance.saveBooks() // 保存最新数据,到本地,下次加载app,删除绘本不再显示 }) alertVc.addAction(sureAction) let cancelAction = UIAlertAction(title: "取消", style: .default, handler: nil) alertVc.addAction(cancelAction) present(alertVc, animated: true, completion: nil) }
内部的实现,封装在PersistencyManager对象中,真个思路就是,第一次启动加载budle中的资源(实际项目中需要加在服务器的数据),然后保存到沙河中,但数据有更新变动时也实时保存数据,整个代码如下: let LibraryCacheDirectory = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first! final class PersistencyManager: NSObject { var books = [Book]() override init() { super.init() let fileName = "(LibraryCacheDirectory)/albums.bin" let fileurl = URL(fileURLWithPath: fileName) let bookdata = try? Data(contentsOf: fileurl) guard let data = bookdata else { // 本地沙河没有数据,所以需要加在bundle中的数据 setupBundleData() return } let json = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [Any] for b in json! { let book = Book(fromDictionary: b as! [String : Any]) books.append(book) } } private func setupBundleData() { let path = Bundle.main.path(forResource: "books", ofType: "json") let url = URL(fileURLWithPath: path!) do { let data = try Data(contentsOf: url) let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [Any] print(data) // print(json) for b in json! { // print(b) let book = Book(fromDictionary: b as! [String : Any]) books.append(book) } print(books) saveBooks() } catch { print(error) } } func getBooks() -> [Book]{ return books } func saveBooks() { let fileName = "(LibraryCacheDirectory)/albums.bin" let url = URL(fileURLWithPath: fileName) let bookDicts = books.map { (book) -> [String:Any] in book.toDictionary() } let data = try? JSONSerialization.data(withJSONObject: bookDicts, options: .prettyPrinted) try? data?.write(to: url) } func deleteBookAt(index: Int) { if index >= books.count { print("数组越界,没有此绘本书") return } books.remove(at: index) } }
感兴趣的可以在github上下载完整代码大家相互交流,整个项目只是我从实际项目中摘取出来的一个页面来讲解,而整个iOS设计模式的内容肯定址这么点内容,后续有时间我应该会更新代码讲解其他的设计模式。我的参考内容有: - 图灵程序设计丛书Objective-C编程之道 iOS设计模式解析
- raywenderlich官网文章iOS Design Patterns
(编辑:52刷机网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|