p67-75: store coredata and realm locally
- Introduce cs/bs architecture
- cs does not need a large number of network connections to improve the software experience.
- There are three ways to store locally:
- userdefaults
- core data - apple comes with a lot of code, not fast enough - not recommended
- realm mobile database recommendation
- Use of core data:
- Create a new project. Click use core data to see what happens to the code and file directory
- Add model files, add entities in the model, and add fields.
- Modify the original code, import Core data, and add some system generated methods (modify the model name);
- The system automatically uses its model file (if the system does not recognize it, an error is reported)
- The method of instance class is changed. sava's method can be directly applied to the appdelegate file.
// core data select data: do{ todos = try context.fetch(Todo.fetchRequest()) }catch{ print(error) } // delete context.delete(todos[indexPath.row]) // For other operations, just remember to save the data
- p70 realm third party database:
- Install Realm using cocopod (failed,
- I found that after the cocopod client was installed, the cdn source was used by default, and the github source was not used,
- I deleted the original library and prepared to rewrite and download one, which was basically immovable, so I tried several methods on the teacher's blog,
- You can't download the zip on github. Finally, find the zip you downloaded. After configuration, it still can't be used. The default address is cdn. So the other way is to use command line to install and Tsinghua source to install realm
- Tsinghua image source website: https://mirrors.tuna.tsinghua.edu.cn/help/CocoaPods/
# Execute the following command $ cd ~/.cocoapods/repos $ pod repo remove master $ git clone https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git master #Add the following line to the podfile file #source 'https://mirrors.tuna.tsinghua.edu.cn/git/CocoaPods/Specs.git'
- Practice the basic use of realm:
let user = User() user.name = "Fido" user.age = 15 do { let realm = try Realm() try realm.write { realm.add(user) } }catch{ print(error) } // It can use realm studio to look at the database print(Realm.Configuration.defaultConfiguration.fileURL)
- p71 Realm added data:
- In the original todo project, use realm to create todo objects, inherit objects, and write properties
- Then instantiate in the global variable and add data in the sava method after instantiation
- Force try, (try!) Make sure this operation will succeed
// user realm create object: class Todo: Object { @objc dynamic var name = " " @objc dynamic var isChecked = false } //create realm object and use try! if you confirm will ok let realm = try! Realm() // add new data to realm database do { try realm.write { realm.add(todo) } } catch { print(error) }
- realm select data
- Result obtained by realm.object < >
- Modify the data type of todos variable
- If the optional value does not exist, set the default value?? One
- In the function of line add, use tableview reload data
// realm fetches data: todos = realm.objects(Todo.self) // change todo datatype var todos:Results<Todo>? //sava data , reload views let todo = Todo() todo.name = name // todos.append(todo) saveData(todo: todo)//New data is stored, and the data in the model is also increased tableView.reloadData() //Re execute the render table method, call tableview cell ForRowAt method
- realm change data
- Modifying the value of an object in todo in the realm write method
- Be careful to use do catch to include code snippets, otherwise there may be errors.
- Click Modify isChecked similar
- Then remember to reload tableView
// Modify the data, re render and load the data: do { try realm.write { todos![editRow!].name = name } } catch { print(error) } tableView.reloadData() // In the table click function: override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if !isEditing{ if let todos = todos // change data all model and database do { try realm.write { todos[indexPath.row].isChecked = !todos[indexPath.row].isChecked } } catch { print(error) } tableView.reloadData() //Change view tableView.deselectRow(at: indexPath, animated: true)// Cancel Click } } }
- realm delete data:
- Method: realm.delete()
// delete data do { try realm.write { realm.delete(todos![indexPath.row]) } } catch { print(error) } // saveData() tableView.reloadData()
- realm search and sort:
- search
- First add a search box in the view, and then implement the proxy of search bar
- How to implement click search box: searchBar searchbuttionclicker()
- In the s method, use the filter method of the result < > object
- Search out the objects we want and update the view
- When users delete all content, they should be able to cancel the search and then take down the keyboard
- Implement searchbar textDidChange method:
- The way to receive the keyboard is to make the search bar lose the cursor, cancel the first response, and put it into the main thread for execution.
- If the database changes, you can only rewrite the installation app to rebuild the data table
- Or find a way to migrate the database;
- sort for sorting
// search button click func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // realm fetches data: todos = realm.objects(Todo.self) todos = todos?.filter("name CONTAINS %@", searchBar.text!) tableView.reloadData() } // search bar textDidChange func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text!.isEmpty{ todos = realm.objects(Todo.self) tableView.reloadData() //In the main thread: DispatchQueue.main.async { searchBar.resignFirstResponder()//Loss of first response } } } // Sort, by createTime todos = realm.objects(Todo.self).sorted(byKeyPath: "createDate", ascending: false)CSUpengyuyan Published 38 original articles, won praise 0, visited 5016 Private letter follow