Mobile Development 20 min read

A Comprehensive Guide to iOS Core Data: Modeling, Persistence, and CRUD Operations

This article explains why Core Data is needed for iOS data persistence, introduces its concepts such as entities, attributes, relationships, and ORM, walks through creating a data model file, configuring NSPersistentContainer, and demonstrates full CRUD operations with Swift code examples and best‑practice tips.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
A Comprehensive Guide to iOS Core Data: Modeling, Persistence, and CRUD Operations

When starting a new project that requires data persistence, developers often reach for SQLite, but the boilerplate code for schema design, logic handling, and debugging can be cumbersome; Core Data offers a higher‑level, object‑relational mapping solution that automatically synchronizes model objects with the underlying store.

Core Data is one of many iOS persistence options. Simple settings can be stored with UserDefaults, archives with NSKeyedArchiver, or raw files, while more complex data such as collections or forms are best handled by SQLite or Core Data. Core Data wraps SQLite, providing a managed object model and a set of APIs that keep the in‑memory objects and the persistent store in sync.

The data model is defined in a .xcdatamodeld file (e.g., Model.xcdatamodeld). Within the model, an Entity represents a table, and Attributes represent columns. For a library example, a Book entity might have attributes name (String), isbm (String), and page (Integer32). A Reader entity could have name and idCard.

Relationships model the links between entities. A borrow relationship from Reader to Book (to‑many) and its inverse borrowedBy (to‑one) illustrate a typical one‑to‑many scenario.

Core Data’s main entry point is NSPersistentContainer. Creating it with NSPersistentContainer(name: "Model") sets up the container for the model file. After initialization, loadPersistentStores must be called to load the underlying SQLite store.

The container’s managedObjectModel provides access to the list of NSEntityDescription objects, allowing developers to enumerate entities and their properties:

let entities = container.managedObjectModel.entities
for entity in entities {
    print("Entity: \(entity.name!)")
    for property in entity.properties {
        print("Property: \(property.name)")
    }
}

Each entity automatically generates a Swift class that inherits from NSManagedObject. For the Book entity, the generated class is Book, which can be used directly in code.

CRUD operations are performed through the container’s viewContext ( NSManagedObjectContext).

Insert : Use

NSEntityDescription.insertNewObject(forEntityName: "Book", into: context) as! Book

, set its attributes, and call context.save() if context.hasChanges is true.

let book = NSEntityDescription.insertNewObject(forEntityName: "Book", into: context) as! Book
book.name = name
book.isbm = isbm
book.page = Int32(pageCount)
if context.hasChanges {
    try context.save()
    print("Insert new book(\(name)) successful.")
}

Read : Create an NSFetchRequest<Book>, optionally set a NSPredicate for filtering, then fetch with context.fetch(request).

let request = NSFetchRequest<Book>(entityName: "Book")
request.predicate = NSPredicate(format: "name = \"算法(第4版)\"")
let books = try context.fetch(request)
print("Books count = \(books.count)")

Update : Fetch the target objects, modify their properties, and save the context.

if let book = books.first {
    book.name = "算法(第5版)"
    if context.hasChanges { try context.save() }
}

Delete : Fetch the objects to delete, call context.delete(object) for each, and save.

for book in books {
    context.delete(book)
}
if context.hasChanges { try context.save() }

Advanced topics mentioned include undo management with UndoManager, fetched properties, handling multiple contexts, and migration strategies, which are left for further exploration.

The article concludes that although Core Data is often perceived as difficult, understanding its design and using the provided examples can make it a powerful tool for iOS developers.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Mobile DevelopmentiOSPersistenceSwiftORMCore DataNSPersistentContainer
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.