Swift Practice: Using CoreData to Complete an Address Book Storage

Swift Practice: Using CoreData to Complete an Address Book Storage

As Apple's own child, CoreData still plays an important role in Apps that need to store structured data. CoreData has been around for more than ten years, and its father is still actively maintaining it.

[[202547]]

If you look at iOS positions on mainstream overseas recruitment websites such as Monster and Indeed, you will basically see that they require proficiency in using CoreData.

However, such a mature and proven code base is not widely used in China. FMDB, Realm, etc. are widely used. During interviews, I often ask iOSers if they know about databases, and the answer is yes. After further questioning, many people only use FMDB and know little about CoreData.

Later I thought about it and realized that it might be because the entry cost of CoreData is a bit high and there is relatively little relevant Chinese information.

In order to write this series, I also bought the book CoreData by objc.io. I benefited a lot from reading it.

I haven’t decided how many articles I will write in this series, but it will probably be a transition from basic to advanced.

The first article uses an address book to read the database. The second article will store more types of data.

The final result:

CoreDataDemo.gif

1. Core Data Architecture

A basic Core Data stack consists of four main parts: managed objects (NSManagedObject), managed object contexts (NSManagedObjectContext), persistent storage coordinators (NSPersistentStoreCoordinator), and persistent storage (NSPersistentStore).

  • NSManagedObject is our data model, that is, the objects we store. These objects are stored in NSManagedObjectContext, and each stored object knows which context it corresponds to.

  • NSManagedObjectContext: This is what you deal with on a daily basis. The other three are only seen when migrating data.

  • NSPersistenStoreCoordinator:

    It is the bridge between the model and the storage database, responsible for hiding the most complex details between the two.

I want to say more about Context, because we deal with it every day. It is actually an area in memory. All operations on objects require a context. Until save, it is in memory and will not have any impact on the content in the database. Each managed object corresponds to a Context, and an object will only interact with a specific Context until the end of the life cycle.

2. Basic reading operations of CoreData

2.1 Five steps to get the data saved by CoreData

  1. Get the general agent and managed object manager

  2. Get a fetchRequest from the Entity

  3. According to fetchRequest, query data from managedContext

  4. Save. Errors may occur during the saving process, which need to be handled.

  5. Add to array

2.2 Basic Storage

  • Get the general agent and managed object manager

  • Create an Entity

  • Save content

  • Save the Entity to the managed object. If the save fails, handle it

  • Save to array and update UI

3. Update a contact list page Demo

Requirement: Complete a list page of address book. Requirements:

  1. Read a list of names from a local database

  2. Click Add to add a name

  3. Added names can be saved to the local database

Okay, let's implement this requirement step by step. To highlight the key points, let's start with the simplest one and use the default project with database.

3.1 Xcode creates a default project with a database

When creating a project in Xcode, a template for creating CoreData is provided. We only need to check the CoreData option when creating it, and Xcode will automatically create the data model file.

This demo was created with this, purely to keep it simple and get straight to the point. Otherwise, if you have to share a lot of other content at the beginning, the readers will get bored.

However, this method is not recommended for actual development. Usually we will delete the generated template code.

3.2 Create a local database template

After checking the box, you will see a file with the suffix "xcdatamodeld", which is our database template.

Of course, we cannot store data in it now, and we still need to set the field name.

  • The first step is to add an Entity, which is equivalent to a table in the database.

  • The second step is to name the newly created Entity.

  • The third step is to design the attributes in Entity. Our Demo only requires a person's name, so we only set an attribute called name, which is of type String.

We will share more attribute types in the following article.

3.3 Query local data

Huh? Didn’t we say at the beginning that a basic Core Data stack consists of four main parts? Why didn’t I see that?

Come on, this is why we used Xcode to create a default project with a database at the beginning. With this option, the corresponding code will be automatically generated in AppDelegate. It does simplify our first learning cost, but just like no one will write all the code in the Controller, you won’t write these things in AppDelegate.

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // Step 1: Get the general agent and managed object manager let appDelegate = UIApplication.shared.delegate as! AppDelegate
        
        let managedObjectContext = appDelegate.persistentContainer.viewContext
        
// Step 2: Create a fetch request let fetchRequest = NSFetchRequest

  (entityName: "Person") // Step 3: Execute the request do { let fetchedResults = try managedObectContext.fetch(fetchRequest) as? [NSManagedObject] if let results = fetchedResults { people = results tableView.reloadData() } } catch { fatalError("Failed to obtain") } }

3.4 Insert and save data to the local database

private func saveName(text: String) {
    // Step 1: Get the general agent and managed object manager let appDelegate = UIApplication.shared.delegate as! AppDelegate
    
    let managedObjectContext = appDelegate.persistentContainer.viewContext
    
    // Step 2: Create an entity
    let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedObjectContext)
    
    let person = NSManagedObject(entity: entity!, insertInto: managedObjectContext)
    
    // Step 3: Save the value in the text box to person
    person.setValue(text, forKey: "name")
    
    // Step 4: Save entity to managed object. If saving fails, process it do {
        try managedObjectContext.save()
    } catch {
        fatalError("Unable to save")
    }
    
    // Step 5: Save to array and update UI
    people.append(person)
}

All the source code is here:

https://github.com/Stanbai/CoreDataDemo.git

Swift CoreData Series 1: Basic Storage

  • Author: Atypical Technology House

  • Link: http://www.jianshu.com/p/3e793fca6a13

  • Source: Jianshu

  • The copyright belongs to the author. For commercial reproduction, please contact the author for authorization. For non-commercial reproduction, please indicate the source.

<<:  Summary of daily development skills of Gradle

>>:  The ninth episode of the Aiti Tribe Clinic: Java, Python, PHP, they all say they are simple

Recommend

Event promotion: How to add 70,000+ new users in 5 days?

This article reviews a user addition case in grea...

Data analysis for event promotion, learn it now

PSM is not suitable for all marketing scenarios. ...

Operation strategy of traffic-generating communities

Community is a relatively important part of priva...

Why is it said that “land, sea and air” are all inseparable from geology?

On June 21, 2024, Gao Jianwei, senior engineer of...

What should I do if my bidding promotion account is maliciously clicked?

Recently I received a private message from a frie...

Nicotine is a drug for longevity? Beware of the pitfalls of subversive research

The rise of self-media has shortened the distance...

Huawei's 5G phones are back, but supply may be limited

The Kirin 9000 chip used in the P50 Pro previousl...