Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Core Data Tutorial

Introduction to Core Data

Core Data is a framework provided by Apple for managing the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.

Setting Up Core Data

To set up Core Data in your iOS project, follow these steps:

  1. Create a new project in Xcode and select the "Use Core Data" checkbox.
  2. Xcode will generate a .xcdatamodeld file. This is where you will define your data model.

Creating the Data Model

Open the .xcdatamodeld file and add entities and attributes to define your data model. For example, you might create an entity named Person with attributes name (String) and age (Integer 16).

Generating NSManagedObject Subclasses

Once your data model is defined, you need to generate NSManagedObject subclasses:

  1. Select the entity in the data model editor.
  2. Go to the Editor menu and select Create NSManagedObject Subclass.
  3. Follow the prompts to generate the files.

Saving Data

To save data into Core Data, you need to create an instance of your NSManagedObject subclass and set its properties. Then, save the context:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
                
let newPerson = Person(context: context)
newPerson.name = "John Doe"
newPerson.age = 30
                
do {
    try context.save()
} catch {
    print("Failed to save: \(error)")
}
                

Fetching Data

To fetch data from Core Data, you need to create a fetch request and execute it using the context:

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
                
let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
                
do {
    let people = try context.fetch(fetchRequest)
    for person in people {
        print("\(person.name) is \(person.age) years old")
    }
} catch {
    print("Failed to fetch: \(error)")
}
                

Updating Data

To update data, fetch the object you want to update, modify its properties, and save the context:

let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "name == %@", "John Doe")
                
do {
    let people = try context.fetch(fetchRequest)
    if let person = people.first {
        person.age = 31
        try context.save()
    }
} catch {
    print("Failed to update: \(error)")
}
                

Deleting Data

To delete data, fetch the object you want to delete, delete it from the context, and save the context:

let fetchRequest = NSFetchRequest<Person>(entityName: "Person")
fetchRequest.predicate = NSPredicate(format: "name == %@", "John Doe")
                
do {
    let people = try context.fetch(fetchRequest)
    if let person = people.first {
        context.delete(person)
        try context.save()
    }
} catch {
    print("Failed to delete: \(error)")
}
                

Conclusion

Core Data is a powerful framework for managing model layer objects in your iOS applications. With Core Data, you can save, fetch, update, and delete data with ease. By following this tutorial, you should now have a good understanding of the basics of Core Data.