CoreData, Apple’s son, still plays an important role in how apps need to store structured data. CoreData has been around for over a decade, and my dad is still actively protecting it.
image.png
If you look at iOS jobs on major overseas job sites like Monster and Indeed, you will find that they require proficiency in CoreData.
However, such a mature, practice – tested code base is not particularly used in China. FMDB, Realm, and more are widely used. I often ask iOSer in an interview if he knows about databases, and the answer is yes. Again, many people only use FMDB, but they don’t know much about CoreData.
Later I thought about it, maybe because CoreData’s entry cost is a little high, and the related Chinese materials are relatively few.
Objc. IO’s CoreData book was purchased specifically for this series. I learned a lot after reading it.
How many chapters will be written in this series has not been decided yet, and it will probably be a transition from basic to advanced.
The first article through an address book database read. The second will store more types of data.
Final results:
CoreDataDemo.gif
1. Core Data architecture
A basic Core Data stack consists of four main parts: Managed objects (NSManagedObject), managed object context (NSManagedObjectContext), persistent store coordinator (NSPersistentStoreCoordinator), And persistent storage (NSPersistentStore).
image.png
-
Ns-managed object is our data model, which is the object that we store. These objects are stored in an NS-managed Object context, and each stored object knows which context it corresponds to.
-
Ns-managed ObjectContext: that’s what you’re dealing with every day. The other three will be seen during data migration.
-
NSPersistenStoreCoordinator: is the bridge between the model and storage database, responsible for the most complex between the hidden details.
I want to say a little bit more about Context, because we deal with Context every day. It’s actually a region of memory that requires a context for all operations on an object. Until save, it is in memory and has no impact on the contents of the database. Each managed object has a Context, and an object only deals with a specific Context. Until the end of the life cycle.
Context is not thread safe.
2. Basic read operations for CoreData
2.1 Five steps to get saved data from CoreData
- Gets the general agent and managed object manager
- Get a fetchRequest from the Entity
- According to the fetchRequest, query the data from the managedContext
- Save. There may be errors during the saving process, so we need to do something about it.
- Add to array
2.2 Basic Storage
- Gets the general agent and managed object manager
- Create an Entity
- Save the content
- Save Entity to managed object. If the saving fails, handle the fault
- Save it in an array, update the UI
3. Update an address book list page Demo
Requirement: Complete an address book list page. Requirements:
- Read the list of names from the local database
- Click Add to add a name
- The added name can be saved to the local database
Ok, let’s implement this requirement step by step. To highlight the point, let’s start with the simplest project with a database by default.
3.1 Xcode creates a project with a default database
image.png
When Xcode creates a project, it provides a template to create CoreData. Just check CoreData and Xcode will automatically create the data model file.
This Demo was created with this in mind purely for simplicity and straight to the point. Otherwise you have to share a lot of other content at the beginning, and the audience will get bored.
However, this approach is not recommended for actual development. Usually we remove all the generated template code.
3.2 Creating a Local Database Template
image.png
Once checked, you will see a file with the suffix “xcDatamodeld”, which is our database template.
Of course, now inside is not able to store data, we also need to set the field name.
image.png
The first step is to add an Entity, which is equivalent to a table in the database.
The second step is to name the new Entity.
Step 3: Design the properties inside the Entity. We only need a name in this Demo, so we just set a property named name, of type String.
Additional attribute types will be shared in the next article.
3.3 Querying Local Data
Yi? Wasn’t it stated in the beginning that a basic Core Data stack consists of four main parts? Why don’t you see it?
That’s why we used Xcode to create a project with a database by default in the first place. Using this option automatically generates code in the AppDelegate. It does simplify the cost of learning it the first time, but just like no one writes all of their code in Controller, they don’t write it in APPDelegate.
override func viewDidAppear(_ animated: Bool) {super. ViewDidAppear (animated) / / step 1: obtain general agent and managed object manager let appDelegate = UIApplication. Shared. The delegate as! AppDelegate let managedObectContext = AppDelegate. PersistentContainer. ViewContext / / second step: Let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Person") / / step three: execute the request do {let fetchedResults = try managedObectContext. The fetch (fetchRequest) as? [NSManagedObject] if let results = fetchedResults { people = results tableView.reloadData() } } catch { FatalError (" fetch failed ")}}Copy the code
3.4 Inserting and saving data to the local database
Private func saveName (text: String) {/ / step 1: obtain general agent and managed object manager let appDelegate = UIApplication. Shared. The delegate as! AppDelegate let managedObectContext = AppDelegate. PersistentContainer. ViewContext / / second step: Establish a entity let entity = NSEntityDescription. Entity (forEntityName: "Person", in: managedObectContext) let person = NSManagedObject(entity: entity! , insertInto: managedObectContext) // Step 3: Save the value in the text box to Person Person.setValue (text, forKey: "name") // Step 4: save the entity to the managed object. Do {try managedobectContext.save ()} catch {fatalError(" Can't save ")} // Step 5: Save to array, update UI people.append(person)}Copy the code
All source code here: github.com/Stanbai/Cor…
One of Swift’s CoreData series: basic storage