Core Data relationships, predicates, and delete rules in Xcode | Continued Learning #16
Вставка
- Опубліковано 22 сер 2024
- In this video, we take a deep dive into Core Data and learn how to create and manage multiple Core Data entities that have relationships between them. We will develop a mock application that contains three types of entities: Businesses, Departments, and Employees. These entities will have many relationships between them, including one-to-one and one-to-many relationships!
In addition to implement the CRUD (Create, Read, Update, Delete) functions, we will learn how to sort and filter (predicate) Core Data fetch requests. We will also learn how to properly delete Core Data relationships by using Deny, Cascade, and Nullify delete rules.
*NOTE: Unlike most videos on my channel, this video is NOT beginner level. You should have an understanding of Swift, SwiftUI, and Core Data basics.*
Learn Core Data FetchRequest: • How to use Core Data w...
Learn Core Data with MVVM: • How to use Core Data w...
Next video: • Multi-threading with b...
Last video: • How to use Core Data w...
🤙 WELCOME BACK 🤙
WEBSITE: www.swiftful-t...
DISCORD: / discord
GITHUB: github.com/Swi...
SAY THANKS: www.buymeacoff...
This is by far, the best SwiftUi Course, and believe me - i tried many. Thank you so much!
I'm very happy to hear this! Glad it's helping you.
My dude was teaching this topic at flipping MIDNIGHT!! The GOAT!!! 🐐
Great lesson brother!
Perhaps the best Core Data tutorial on UA-cam. Great job, Nick 🥇
Thank you! These are the best SwiftUI videos. Even with poor English, everything is crystal clear!
I am very happy to hear this! Thanks for watching :)
There is one thing Nick missed to mention - ALL relationships in this example are OPTIONAL!
Otherwise it will not be possible to save/add 'business' without 'departments' and 'employees'.
It would be good if at least 'employees' were not optional.
The quality of these tutorial is incredible. You have a gift! Small number of people can explain something complicated like CoreData with this clarity. Great work 🎉
Thank you very much Mr. Sarno, this explained everything that I needed to know to get past this hurdle.
Another awesome video. As others have said in the comments below, I too spent quite a bit of time watching videos and reading articles on relationships, predicates, and such in CoreData but found that there were either a lot of gaps or assumed knowledge. This is an excellent intro to advanced CoreData. Very grateful. Thank you!
Thanks Drew!
This is the exact video I needed, very clear and great explanation about how to use core data and managing the relationship between multiple entities. Also I would say one of the only videos I have found clearly describing a Many To Many relationship. Thank you so much!
This is a very interesting explanation of a complex subject, and an excellent example of the power of mvvm in action. It is very easy to follow because it builds on lessons from your previous videos. You put a lot of time and effort into this video the result is excellent. Thank you
Thanks for the comment Paul! Yea this was one of the harder ones to record because I wanted to get it all into one video. I'm glad it was helpful!
I must say that this is the best SwiftUI course for beginners. I’ve tried some on Udemy and quite a few on UA-cam, but your course beats them all. Congratulations! 🥳
I am a beginner, and I was stuck on a problem with Core Data that was preventing me from progressing in my project. This issue had been bothering me for a long time. Thank you, teacher, for your video, which has helped me make further progress in my project. I am extremely grateful.
This is by far, the best and most understandable video about CoreData I've ever watched! A big Thank you !
Many thanks for this epic video tutorial on Core Data relationships in such a learner-friendly manner.
This is the only effective explanation of Core Data relationships i have found. Excellent work!
We are now CoreData experts. Thank you so much!
Best, easiest coredata tutorial ever. Like this so much! Even if your video is so long, I am enjoying this
Haha thanks for the comment Dzulqarnain
Wow... This is the best Core Data Course I've ever seen.
I want to understand this topic for a long time~~Finally~~~
You really do a excellent job~!
Thanks you for welling to share this complicated knowledge for everybody!!
Hello Nick, just wanted to show my appreciation of your thorough explanation, thank you. And please keep up the amazing work!
This is the best SwiftUI course i've ever seen, Thank you soooooooooo much!
9:12 The real start of the video. Up to that point, it is setting-up CoreData, which you have probably seen before if you're watching this video!
I’ve been stuck trying to rewrite an old Objective-C based Core Data app. This is exactly the explanation I needed to move forward!
Thank you for the video. Best video on this topic i have seen so far.
Long, but excellent! (As usual.) It's a video that will take reviewing, probably several times, but not until I need to use Core Data relationships myself. I also benefitted, though, from the repeating of entering similar code, because I got used to the basic structure of the different blocks. Thanks so much!
I was planning to use Realm for offline data in my app. But changed the decision watching this video. CoreData is really powerful. Thanks to you for presenting it with easy explanation.
There are many devs who would argue for Realm over Core Data, I personally choose Core Data every time. It also keeps ur bundle size smaller 🤙
It's just a masterclass! Watched this video like a new movie
😎 Thanks Vlad
this is the best video on Core Data. Thank you ☺
Great, excellent, wonderful. This is the best course I have ever seen. Keep it up. I look forward to every episode.
Wow! Thanks for the support Felix. I'm happy to help. In the next section of the course we will jump into downloading data from the internet, which should be even more exciting than this :)
So far the best video on the subject matter, by far. I learnt a lot, but like most things only practice and making mistakes will ingrain it.
So true! CoreData is tough lol even after using it a while I still run into mistakes sometimes 😅😂
Thanks for this long tutorial very interesting, it is the first time I see Core Data with relationships easy to understand !
To fold structures you can setup Xcode preferences and select, text editing code folding ribbon it is easier but you probably know it
No need for apologies, excellent tutorial and explanation. Thanks
man I was stuck on exactly these problems, I had exactly 3 entities that relate to each other and I was banging my head against the wall. life saver. amazing tutorial.
Happy to help!!
The CoreData tutorial is excellent, Thank you!. Now, SwiftData looks very convenient and powerful. I'm very interested in learning more about it. Please add a chapter on SwiftData tutorials, please!
amazing tutorial, you';re on the path to become the next hacvking with swift!
Wonderful video. Very clearly explained. Will have to give you some coffee money to keep up the good work!!
thanks for this deep dive Nick !
Perfect explanation! Thank you!
Excellent course and this was a superb video. Thanks
Thanks Frank!
So well explained ! Many thanks
Awesome!!! Really great thanks! So simple to understand.
Great video. Thank you. Have you ever considered doing a many-to-many video where there is an attribute in the intermediate table? Like a Person/Rating/Restaurant or an Ingredient/Measurement/Recipe, etc.
WOW! Excellent video! great presentation and probably the best explanation of Core Data I have seen. Is you source code available? You sir are a breath of fresh air in the swiftui educational arena. THANK YOU!
Hey Dave! I am very happy to hear that! The source code for the entire playlist can be found on my Github: github.com/SwiftfulThinking 🥳
Wow, what an awesome video. It's going to be so useful for a data App that I am trying to build.
I did want to delete records by name rather than by index value.
My attempt generates an error after 'manager.context.delete (business) - "No exact matches in reference to static method 'buildExpression'. Here's the function>
func deleteBusinessName() {
let request = NSFetchRequest(entityName: "BusinessEntity")
let filter = NSPredicate(format: "name == %@", "Halfords")
request.predicate = filter
do {
businesses = try manager.context.fetch(request)
} catch let error {
print("Error fetching Business Entity \(error.localizedDescription)")
}
ForEach(businesses) { business in
manager.context.delete(business)
save()
}
}
🔥🔥🔥 Nick, cool Course. Thank you so much!
Great tutorial, very clear.
Thanks for watching beader chen! 🥳
Awesome. Loved it.
Nick, as always, great tutorial with excellent content. Many, many thanks!!! That said, coming myself from ERP systems running MS SQL Server (or similar relational) databases I was wondering if SwiftUI could be used to build a relational database type of application. With what I have seen so far of Core Data I'm inclined to believe the answer is yes. Core Data seems to be a very powerful and user friendly database and the best of all is that it is included in Xcode. Thanks again for all the great content.👍👍
Such masterpiece!
Thanks Willow!! :)
What a difficult concept to understand. Very in-depth and very well done. Not sure I’ll retain it all but I’ve been waiting for the Core Data courses and this was fantastic. Stop apologizing. LOL
It was a long one I had to apologize haha. I wouldn't worry about retaining it all because this isn't as common as the other videos in this playlist. However, if you ever need to implement this, you could probably come back and refresh quickly!
Excellent video, many thanks for sharing your knowledge with us!
Great, thank you so much!!!
You're welcome!
Honestly I struggled to follow this one, but then again I am a beginner. That being said it's still clearly a good video and I've enjoyed all the videos so far. Perhaps this is one I'll end up returning back to at a later date.
The video was good Nick. My feedback for this type of video is to suggest not starting from scratch. You could have the basic layout in place-perhaps even with sliiiightly snazzier UI (even if that totally isn't the point)-and have ready-made, smallish buttons for the CoreData interactions and functions (not the code, just the UI). That way it would be a little less hardcoding, and perhaps even fewer distractions from small code updates back and forth.
I think you have to be free to say "this video focuses on CoreData concepts and functionality" and just skip much of the stuff people are supposed to know at this point.
Really good tutorial, I really thought Core Data was harder, you made it look so easy that I will start using Core Data instead of Realm. You're good at teaching, keep up the good work. Hopefully one day you can make a tutorial on Core Data, CloudKit and SwiftUI. Thanks for the good tutorial.
Thanks for watching! Realm is also great though. I am just trying to teach the Apple APIs first :)
@@SwiftfulThinking I really like Core Data. After watching your tutorials I see no reason to use Realm anymore , bye bye Realm. Thanks a lot for the good tutorials.
Nick, I love your tutorials, and have followed several of them. However,, this tutorial has a lot to unpack, even for the intermediate developer. My recommendation would be to break this tutorial out into two separate tutorials. The first tutorial would be a strict one-to-many scenario (using your grandfather-father-son relationships). The second tutorial would be a realistic many-to-many scenario (such as students-courses). There is enough to unpack with each of these tutorials. By adding a man-to-many relationship between businesses and departments, as well as the three levels of relationships, I find may be challenging for the average noobie. Just a suggestion. Notwithstanding, I will follow all of your videos. Your narrative explanations are clear, informative, and very easy to follow.
Really excellent course! 🙏🏼
Phew - made it through! Was heading to the pub tonight, but had to finish this, so stayed home!
Thank you Nick. Fantastic.
Do you have any courses on Udemy?
You are the best👍
Great questions as always. This is all async code, so timing is definitely a concern. When the app is launched, the CKContainer is automatically set up. We aren't setting that up with these functions. So that app is already connected to CloudKit. The function getiCloudStatus() is then checking if the current user is signed in to their personal Apple ID account on the device. This is required for them to access CloudKit (but CloudKit is technically connected to the app already regardless). This should be the first call and generally will always success - I don't know anyone on an iPhone that isn't signed in to an iCloud account. However, I would have some UI in the app that if this function fails, stop everything else and show a screen that says "you need to sign in to your iCloud account". After that, we can call requestPermission() to check if the current user has granted the app permission to access their personal user information. In production, I would probably sequence these events one-after-another just incase. More practically though, getiCloudStatus() might be something called at app launch (in App Delegate or something) and then getiCloudStatus() might be called during onboarding or something like that.
01:10:00
delete rules in Xcode
You are the best
Nick, you are great ;-)
Thank you so much
Amazing!!
You are best teacher
Far from the best, but I'm trying! Thanks for watching :)
Definitely enjoyed this video and learned a lot however I had to constantly fight against my brain from trying to procrastinate and just click away every few minutes. Thank you!
Haha you got this! I know this was a long video
Just amazing! Thanks it was very clear!
Great video! However I would love to know more on how to to create a button on each stack so that I could perform the delete action directly from there instead of inputing its index.
You could probably use the same delete function and just find the items index when you click on it!
Nice!
• You can add ⚠ -_UIConstraintBasedLayoutLogUnsatisfiable NO in Edit Scheme Arguments to hide conflicts in console
• for a better presentation, use an iPad
Awesome video! One thing I missed was the Core Data and threads (because I am trying to learn Core Data and Swift in general and heard a mention on podcast that Core Data is hard to use with threads and might cause crashes), but maybe the topic would not fit in your video.
Hi Alexander, this is a great comment. In this video (and in most apps I've seen) CoreData is managed on the main thread, so there are no issues. However, you do need to be careful in a multi-threaded environment. I'm going to add on my a list for a more advanced bootcamp course!
Why does everyone write all the code inside the ContentView? Nobody makes subviews in other files, and I only found one that did the views but did not create the previews to see them on canvas. And some videos do not follow the way of doing it in the previous one, when they do CoreData explanation sequences, do you recommend a book of complete MVVM examples? Thanks in advance.
Thank u so much for this videoo
Thanks for saving my bacon again
Felt like a workout doing that one
Just one question on 39:20 - why does it need dispatchmainqueque? I tried without it and it didn't reload the screen properly, so i couldn't see the department being added... Just wondering, why it needs this delay.
Great question. It has to do with the way we set up the view hierarchy for the example project. Without it, the ForEach statements aren't being told to refresh. It was just the easiest way to get through this video. When using this in a production app, you will probably have a very different screen and architecture, and you shouldn't have to add the delay. I hope this wasn't too confusing haha
Great video. I am trying to replicate this example using 3 entities that all have many to many relationships with each other.
I’m struggling to retrieve linked data from all three entities via the relationships. Any tips on how you would do this?
Thanks for an excellent video Nick! Quick question: do you know if apps like Facebook, insta, tiktok would use core data relationships ? Do you know what sort of apps will use CoreData relationships ?
Great video! All the examples I’ve seen of adding, updating, or deleting an entity call save and then refetch all the data for that type in update the local array of entities. That seems inefficient for large collections. Is there another approach that would just update the local array by adding one entity, updating one, or deleting one?
Hey Mark, yea the other approach would be updating the array directly. For example, if you are adding a new item, you could 1) add it to CoreData and 2) simply append the item to the array without reloading. I was reloading here to make sure the database is updating correctly. If you do this other approach, you just want to make sure that your CRUD functions are completing successfully. For example, if you add an item to CoreData but it fails to save, you would want to make sure it's not still showing on the UI.
Hi,
Did you create the let context: NSManagedObjectContext in the CoreDataManager class only for the for convenience in order to avoid writing manager.container.viewContext.fetch(request) or what is main purpose of it?
A quick question.
What if I want to fetch only the high-level Entity(table) and when the user goes to the specific table view then I fetch the data of the related table?
Because if there is a lot of data in the secondary table I don't need to fetch all that since the user didn't ask to see it.
Great Vid! Question though... In your app and from previous video, you created instance of NSPersistentContainer (let container: NSPersistentContainer) for the Fruit container.. In this vide you created another one.. Are you allowed to declare two NSPersistentContainer or two containers (e.g. FruitContainer and CoreDataContainer like your example)? Is this allowed? I just tried it and won't compile.
Instead of using a singleton for CoreDataManager is it Ok to use it as an EnvironmentObject?
Hi Usha, yes you can structure your code in whatever way works best for your app. I used a singleton here just to make it simple.
but, starting xcode 14 apple just removed editorStyle for coreData, looks so strange
Hey Nick, great video again!! Do you know if there is a way to set the delete rule via code so it is also possible to let the user choose what he prefers?
Hey Malbo, that is a great question! I don't think it is possible though. Even if it was, it's probably not something you would want. As the developer, it's pretty important that you have a solid understanding of the CoreData (or any other database) that your users will be using. This way if you need to make updates, you know exactly how their data will be structured. If all of your users had different rules in their CoreData, it would be extremely difficult to update and maintain as you iterate on your app.
Is AWS DataStore or Firebase Firestore a viable replacement for Core Data? It seams like managing the age and refresh of data manually is a lot of work?
Hello, why are you not using 'private' for init() in singleton class?
As usual, your video's are awesome and you explain them very well.. thank you... I accidentally signed up to the monthly fee, when I meant to pay you on an ongoing basis every now and then as I watch video's.. can you cancel my monthly fee membership and I can assure I will pay you ongoing fee's as I view your wonderful video's ... thanks again...Bob
Hey Bob! Sorry for the delay. Firstly, thanks for the coffees! .... I just cancelled your membership. You should also be able to sign in and manage your account on www.buymeacoffee.com/nicksarno. The memberships should all be cancel at any time 😅 Anyway, cheers!
What's the purpose of businesses.removeAll( ) and departments.removeAll( ) within the save( ) function?
@SwiftfuThinking please can you explain ?
I found the answer !!! @lolrie : nick remove the content of observed arrays and then get data from core data to fill them. I don't try without the trick
I have Xcode 15 and Editor/Style switch is missing so I can not see a graph. Did someone solved the same issue?
Great videos, very clear! I am a beginner to ios programming, and feels so confused about storing color in Core Data, can you make a video abou that, thanks a lot. Like how to store the selected color from the ColorPicker() to Core Data.
Sir i get an error, the card(name, department and employee) doesn’t show below the button. Sir I followed you step by step. The Card appears after the button when i call the addBussiness() in the init function. Sometimes it shows two cards with same data in Hstack. I’m so worried please help.
Hi guys! How to delete relationships correctly. I don’t need more some relation between entities. I just remove it in the next version of model, but data loses. Please help!
I got confused and made mistakes, but in principle the same))
super useful! thanks. By the way, as I was working on this, I got "appleaccound quit unexpectedly" 20 times. Have I not set something correctly?
Hey Nick you haven't created a private initialiser but you are saying it as a singleton Can you pease clarify me about this?
Hi Nick
can you create some example searchable using multiple objects like start date and end date for fetch filtering? Thanks You
I'm learning Coredata + SwiftUI and I was wondering if I could ask you a question.
I am developing an app to record clothes information. Which way is better, to convert the image to a binary data type and store it in core data or to store only the URL of the image in core data and the image file in a document file?
Store the URL to CoreData and save the image to the FileManager or use an image SDK
@@SwiftfulThinking Thank you for your response. I was storing the images in JPEG compression, but it was allocating a very large amount of memory from the core data when the number of items increased.
I tried to improve it with the above link, but I'll try to implement it in the way you suggested, since I'm applying the cloud kit and I also need to consider how to store the images in a document file and how to handle if the user deletes them from that path by chance.
Thanks for the advice. You are like a god to me as a self-taught developer. I respect you.
not sure why but when I hit save the view doesn't reload
Shouldn't there now be 2 businesses named Apple at 34:00 ?
Hi nick, i need urgent help in one of my core data app with current xcode, how can i reach out to you?