Core Data: Beyond the Basics

Jul 26 2022 · Swift 5.5, iOS 15, Xcode 13.3.1

Part 2: Advanced Core Data

18. Deleting Launch Lists

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 17. Delete Rules Next episode: 19. Storing Large Files

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 18. Deleting Launch Lists

Navigate to your data model, the RocketLaunches.xcdatamodeld file. Earlier when you set up your entities you skipped a section or two. Let’s go back to those. Select the launches relationship in the RocketLaunchList entity and switch over to the Data Model Inspector. In the second section you should see a Delete Rule option and it should be set to Nullify by default. You’re going to change this to Cascade. Now when a list is deleted all associated launches will be deleted as well.

Next, do the same for the list relationship defined in the RocketLaunch entity. This one you’ll set to No Action.

If you build and run the app, and add a list if one doesn’t exist, you’ll see there is no clear way to delete the lists. Navigate to ListView and at the very bottom, you’re going to add a few methods to enable row deletion.

The first method you need to implement is delete which informs the List view how to handle the deletions of specific rows in the list:

func delete(at offsets: IndexSet) {
	let lists = offsets.map { self.launchLists[$0] }
	do {
	  try PersistenceController.deleteList(list: lists[0])
	} catch {
	  print("Error deleting list")
	}
	}

Secondly, you need to add a modifier to the ForEach:

.onDelete(perform: delete)

Open PersistenceController and define the deleteList function you just used.

static func deleteList(list: RocketLaunchList) throws {
	let taskContext = shared.container.viewContext
	taskContext.delete(list)
	try taskContext.save()
}

This grabs the shared container’s context, and then instructs the context to delete the list. You ask it to commit those changes by calling the save method.

I’m being a bit lazy here and avoiding error handling code, but you know what to do.

Build and run the app. Now you should be able to delete any list and have the associated launches be deleted as well. Just as a reminder this only works because you implemented part of the logic earlier.

That’s it for deleting. Pretty easy right? In the next video let’s talk about persisting large chunks of data.