Swift Data Relationships 🚀 | SwiftData Tutorial | #2

preview_player
Показать описание


Relationships In SwiftData 🚀 | Adding Categories To A To-Do App, SwiftData Tutorial

Build A To-Do List App using SwiftData (Swift Data Tutorials) - Free Course

**********************************

*Timestamps:*

00:00 - Intro
00:32 - 🚨🚨🚨Warning
01:03 - What Is A One To Many Relationship
02:11 - How To Setup A One To Many Relationship in SwiftData
06:23 - How To Save Categories in SwiftData
07:19 - How To Fetch Categories in SwiftData
08:32 - How To Delete in SwiftData
09:41 - Fixing A Crash With Relationship Deletions
12:41 - How To Save Data One To Many Relationships in SwiftData
19:44 - Update A Relationship In SwiftData
23:20 - Handling empty states with SwiftData

**********************************

Now that we have SwiftData, you may be wondering. "How can I relationships in SwiftData". Don't worry I've got you. In this SwiftData Tutorial, I'll be showing you how to work with SwiftData Relationships specifically a one-to-many relationship in SwiftData.

We'll be building categories for our SwiftUI To-Do App, and give users the capability to create new categories and attach them to a todo. We'll also take a look at how to CRUD operations with a SwiftData relationship so that we can update our categories.

**********************************

*Check Out My Courses 👨🏽‍🏫*

Enjoy my teaching style? Check out my other courses on my website that may interest you, they range from beginner to advanced topics within iOS development.

*Link to Website*

**********************************

*Join the crew 🤝*

Want to help support the channel? Become a member with the join link below and get access to exclusive badges and stickers, as well as other perks that are coming soon.

*Become a channel member*

*Support in other ways 💕*

You can support me for free and help the channel grow so that I can continue to make the best iOS development content for you by liking, commenting, subscribing, and hitting the notification bell.

All of this really helps my channel grow and allows me to keep on making content for you. If you’re interested in subscribing to the channel then you can do so with the link below.

*Subscribe to the tundsdev YouTube channel*

**********************************

*Download Source Code*

Interested in looking at the source code? Then check out the GitHub Repo below

**********************************

EditorKeys
View Editor Keys Amazing Products with the link below and use the discount code for 10% off any product

Get a 10% Discount Code on any product with the code below
TUNDSDEV

See my keyboard cover in action with my review below 👇🏾

**********************************

RØDE Wireless Mic

RØDE SmartLavPlus Microphone

2021 Apple MacBook Pro (16-inch, Apple M1 Pro chip with 10‑core CPU and 16‑core GPU, 16GB RAM, 1TB SSD) - Space Grey

Apple Magic Keyboard with Numeric Keypad (Wireless, Rechargeable) 

Apple Magic Mouse

Secretlab TITAN 2020 Charcoal Blue Gaming Chair

ErgoFoam Ergonomic Foot Rest for Under Desk

Lumbar Support Pillow

Macbook Stand for Apple Macbook and All Notebooks

Portable Chair Green Screen Background

**********************************

#iosdev #iosdevelopment #swift #swiftlanguage #xcode #appdevelopment #mobileappdevelopment #iosappdevelopment #appdeveloper #iosprogramming #iosengineer #appdevelopmenttips #iosdevelopmenttips #swiftui
Рекомендации по теме
Комментарии
Автор

⚠ The crash at 9:41 is a known issue & has a workaround also by calling modelContext.save() after the deletion of an item

tundsdev
Автор

Solid tutorial and great explanations!! 💪🏾💪🏾

marcaupont
Автор

Nice video, could you perhaps complete the serie and add many to many relationships too? For example let's say insert sub-todo or I mean list into this list, I will really appreciate that. Thank you so much ❤

mkhasson
Автор

One additional comment on this and I’m reluctant to share as I’m grateful for what you do!

Having said that, the coding for this is confusing if you are following these videos in sequence. I completed the first video and then moved on to this. I assumed I could simply continue with the code base as we left at the end of the last video. Wrong assumption. I kept finding pieces of code that were either missing or changed from the first video. Finally realized during the segment when you added the save function that I’m missing a bunch of code. I need to scrap and start over using the git samples for this video. I think this could be explained better. I feel it is a logical progression to move from one video to the next while continuing the same project.

I hope that makes sense.

jayelevy
Автор

Great video Tunds. I think the crash you are experiencing may be tied to the new autosave feature implemented with SwiftData. I can consistently get my code to crash by deleting after an insert. To solve this, after the code to perform an insert:  

.insert(task) or .insert(category)

Place an explicit call to the modelContext to save inside a do...catch:

do {
try modelContext.save()
} catch {
fatalError("Fatal error saving in function/class \(error),


I know it's not ideal, but I can't get the app to crash anymore. Maybe Apple will fix this in future betas.

cloftis
Автор

This was really helpful, I was about to bang my head into a wall after the worst relationships examples given in WWDC23. Thanks a ton

abhishekthapliyal
Автор

Thanks for another great tutorial!

Despite taking your advice and adding the code to set category.items = empty array and set title = empty string when adding a category, I'm still crashing when deleting a newly added category. The problem seems to be because we are trying to access the title property of a category item that may have already been removed due to the ForEach loop?

Any ideas?

ChristopherDisdero
Автор

As of Xcode 15 beta... 4? 5?, the @relationship macro requires a deleteRule tag, i.e., at 5:01, you need...

@Relationship(deleteRule: .nullify, inverse: \Category.items)

(I just noticed that this is mentioned in the comment regarding the crash at 9:41, but I wasn't even looking at that that since I was seeing problems at 5:01.)

bobgilmore
Автор

Thanks for the video! Brilliant tutorial, but is there something missing just before 8:10? I couldn't see where you added the new buttons to the main view?

mrchumley
Автор

My version of the button.

// START - New ToDo button
VStack {
Spacer() // Push content to the right
// New ToDo button
Button(action: {
showCreate.toggle()
}) {
HStack {
Image(systemName: "plus.circle.fill")
.foregroundColor(.blue) // Icon color

Text("New ToDo")
.foregroundColor(.blue) // Text color
}
.padding(.vertical, 10)
.padding(.horizontal)
.background(Color.white) // Button's background color
.cornerRadius(20) // Pill shape
.shadow(color: .gray, radius: 2, x: 0, y: 2) // Shadow for depth
}
.padding(.trailing, 180) // To match the floating button's right padding
.padding(.bottom, 20) // To match the floating button's bottom padding
}

josephestrada
Автор

Yet another great set of videos! Thank you for what you do.

I am getting an error “Type ‘Schema.Relationship.Option’ has no member ‘nullify’” in the Item model definition on the @Relationship line (code copied directly from your git). I’m wondering if this is a beta bug? Though, I’ve searched and see no reference to this. I’m stuck.

jayelevy
Автор

Do you mind explaining the property wrappers? All of these new ones are throwing me for a loop? @Bindable vs @Query is the thing that is catching me off guard. So you create the model on the class with @Model but you link it with @Query? If you want to change something is that when @Bindable comes into play?

Yes that helps! Thank you. Also real credit to you to respond to comments so quickly.

Ride
Автор

In Xcode 15.4, I am encountering errors at 7:05. The error reads: "Struct 'ViewBuilder' requires that 'EmptyTableRowContent<V>' conform to 'View'" and Static method 'buildExpression' requires that 'TextField<Text>' conform to 'TableRowContent'. It would be great if you could update the app using Xcode 15.4 for iOS 17.

Echaront
Автор

Hello Brother,
I have one Question ❓
I want to provide an icon & color at the time of creating todo.
For that i had created antother view which had all SFsymbols, which is presented in sheet from where I can select the icon & that icon should be selected on the create todo view. But i m not able to do that.
I way I was able to achive that result was buy create a model for Icon, same as you did for category. But that will use extra resources on the app, because I had created the relationship for Icon with TODO. Not is not approprate.
Because we have all icon in sheet & from that sheet we just want that which icon was selected & should add that icon name String into todo.
We cant append icon into todo because we have not still created new todo.
Home View → Create Todo View → Icon Sheet → Create Todo View
If I have 10 to 20 icon I can make array in the Create Todo View & that will work. I can do that. But I cant pass selected icon from Icon Sheet to Create Todo View.
Can you make a Video 🎞 in which we can you can add icon & color on create category or create todo view.
And categories should also not be on create todo view. If they are with the page we are able to select. But if we move it to another sheet we are not able to select it from there. So please also extract category selection from another sheet. In real apps user has lot of categories.

akbar.n
Автор

Github repo is missing from description

DavidM
Автор

First person to spot the mistake in the intro wins nothing

tundsdev
Автор

Nice video! and can I know the .onAppear{} and .onAppear(perform: {}) is exactly same?

lfan_tv
Автор

Update the relationship by adding deleteRule:
@Relationship(deleteRule: .nullify, inverse: \Category.items)

teakodo