Core Data In SwiftUI | SwiftUI Core Data Tutorial

  Переглядів 20,874

tundsdev

tundsdev

День тому

Core Data In SwiftUI | SwiftUI Core Data Tutorial
🚨Improvement🚨
In the vid you'll see in the ContactsProvider.swift file I create a new context using the background context function. Can you replace these lines with the following below to create a new context on the main thread for better thread safety.
var newContext: NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator
return context
}
**********************************
Timestamps:
00:00:00 - Intro/Preview
00:01:15 - What is Core Data?
00:02:18 - How To Add Core Data To An Existing Project In Xcode
00:04:25 - Creating Entities data in Core Data
00:06:15 - Modelling your data in Core Data
00:08:41 - Create your own Core Data Model Manually In Xcode
00:13:47 - Creating a Core Data Stack in SwiftUI
00:29:16 - How to Save Data In Core Data In SwiftUI
00:42:05 - Breaking down NSFetchedRequest
00:44:47 - How to Fetch Data from Core Data In SwiftUI
00:46:46 - Hooking up our UI to our Managed Object
00:51:22 - How To Save Data To Core Data In SwiftUI Using The Environment
00:57:31 - How to pass Core Data Objects Between Screens In SwiftUI
01:00:26 - Setting up SwiftUI Previews with Core Data
01:12:00 - Creating An Empty State For Core Data In SwiftUI
01:15:49 - Setting Up Swipe Actions In SwiftUI
01:18:05 - How to delete data in Core Data in SwiftUI
01:23:08 - How To Update Data In Core Data In SwiftUI
01:32:03 - Advanced Core Data Topics & Breather
01:32:31 - Improving And Refactoring Our ContactsProvider
01:41:18 - Improving our Persistence & Validation In Core Data
01:46:07 - Filtering Data in Core Data with a search bar in SwiftUI
01:53:32 - Filtering Data in Core Data with a Menu
02:04:30 - How To Sort Data In Core Data In SwiftUI
02:08:57 - Unit Testing In Core Data
02:26:23 - Code Coverage
02:27:42 - Summary
**********************************
Are you looking to learn more about Core Data and how to use it with SwiftUI in your iOS projects? Look no further! In this swiftui core data tutorial, you'll get over 2hrs of content covering everything you need to know about how to work with core data in swiftui.
I'll introduce you to Core Data and explain what it is and how it works. You'll also learn how to perform essential CRUD (create, read, update, delete) operations in SwiftUI and how to sort and filter your data.
In addition to working with Core Data, you'll also learn how to use SwiftUI previews. We'll also show you how to implement unit testing with Core Data.
This tutorial is perfect for anyone looking to get started with Core Data and SwiftUI in their iOS development journey, or for experienced developers looking to improve their skills.
If you want to try out the final app, you can download it using the link apps.apple.com/gb/app/my-best...
**********************************
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
tunds.dev/#courses
**********************************
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
www.youtube.com/@tundsdev/join
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 UKposts channel
ukposts.info?su...
**********************************
Download Source Code
github.com/tunds/youtube-cont...
**********************************
EditorKeys
View Editor Keys Amazing Products with the link below and use the discount code for 10% off any product
www.editorskeys.com/tundsdev
Get a 10% Discount Code on any product with the code below
TUNDSDEV
See my keyboard cover in action with my review below 👇🏾
• Increase Your Xcode Pr...
#iosdev #iosdevelopment #swift #swiftlanguage #xcode #appdevelopment #mobileappdevelopment #iosappdevelopment #appdeveloper #iosprogramming #iosengineer #appdevelopmenttips #iosdevelopmenttips #swiftui

КОМЕНТАРІ: 100
@tundsdev
@tundsdev Рік тому
Source Code is available in the description box, lemme know your thoughts do you like Core Data too? 👀
@davidlampert2910
@davidlampert2910 Рік тому
As I was playing around with this, I found something strange... is there a defect in the isBirthday logic? Appears to only mark birthday as true on the actual day/date/year of birth, not future bdays? I updated to the following and it seems to work for me. I'm sure this could be "cleaner" but I'm fairly new to swift. Thanks again for all your great content... var isBirthday: Bool { let calendar = Calendar.current var dobComponents = calendar.dateComponents([.year, .month, .day], from: dob) let todayComponents = calendar.dateComponents([.year, .month, .day], from: Date()) if (dobComponents.month == 2 && dobComponents.day == 29 && todayComponents.isLeapMonth == false) { dobComponents.day = 28 // Set bday to 28th for leap baby } return (dobComponents.month == todayComponents.month && dobComponents.day == todayComponents.day) }
@MichaelNinoEvensen
@MichaelNinoEvensen Рік тому
This is awesome! Thank you so much for putting together this video, it's super comprehensive and I love the fact that you've tackled real-world use cases 👏
@tundsdev
@tundsdev Рік тому
Glad you enjoyed it
@simonIsDev
@simonIsDev Місяць тому
i finished after 3 days immersive on your course, it's very useful for me, thanks at all
@tundsdev
@tundsdev Місяць тому
Glad you’re enjoying the content!
@WilfClegg
@WilfClegg Рік тому
I've been a computer programmer since 1967 (IBM 1401 Autocoder)...I worked with COBOL and Fortran for the next 30 years, then moved into Visual Basic, then finally Swift during the last 25 years. (lots of experience in the programming world). I've taken many Udemy courses and followed many UKposts courses. Tunds, your video is the most professional, operational, and production-ready I've encountered to date. Extremely well done, my new friend! I will join your website, and help you out! Wilf (in Canada)
@tundsdev
@tundsdev Рік тому
Oh wow that’s really nice of you to say Wilf, I’m glad you enjoyed the video & find value in my content 🤝
@WilfClegg
@WilfClegg Рік тому
@@tundsdev Sincerely, the pleasure is all mine, Tunds, thanks again. I’m having a little trouble, though, joining your web page. Is there a sign-up link, that I’m not seeing? Wilf
@tundsdev
@tundsdev Рік тому
Hey man, so I don’t have a sign up on my website it just lists my courses. If you want to support me you can become a youtube member by hitting the join button on my profile 🤝
@WilfClegg
@WilfClegg Рік тому
@@tundsdev Yes, already done, my man! 👍
@WilfClegg
@WilfClegg Рік тому
Also, I love Core Data! It’s a “front end” for MySQL. I’ve taught the relational database model to many junior programmers, through the years. I prefer it to the hierarchical model (Firebase, and JSON, for eg). However, we do need to learn all of them. 🥴
@sleepW993
@sleepW993 Рік тому
I've been looking for a video like this for a few days thats amazing thank you!
@tundsdev
@tundsdev Рік тому
Awesome glad you enjoyed it 🤝
@oliverbarreto1838
@oliverbarreto1838 Рік тому
Happy new year !!! And thanks for sharing !!! You just read my mind cause I was just searching for your videos on core data topic 💪🏻😃😎❤️🎉☀️👍🏻
@tundsdev
@tundsdev Рік тому
Awesome hope you enjoy it & happy new year 🍾🎉
@ayonut4022
@ayonut4022 3 місяці тому
Thank you SO much for this video! It has been a great help for my school project! I can finally claim that I do understand SwiftUI and CoreData a little bit better :DD
@tundsdev
@tundsdev 3 місяці тому
Glad it helped!
@FloWritesCode
@FloWritesCode Рік тому
Aaaaaaand he's back! Great work, I can only imagine how many hours you sat there editing this course...
@tundsdev
@tundsdev Рік тому
Thanks man & I wanna say 3 days 😅😂
@davidlampert2910
@davidlampert2910 Рік тому
Great class...thank you so much for your content, I have learned a ton!
@tundsdev
@tundsdev Рік тому
Glad you found it useful 🤝
@abdouett3676
@abdouett3676 Рік тому
Thank you for sharing!
@tundsdev
@tundsdev Рік тому
No worries, enjoy 👌🏾
@Dissident.Dissidentovich
@Dissident.Dissidentovich Місяць тому
Thanks friend, amazing tutorial! CoreData is new for me :)
@tundsdev
@tundsdev Місяць тому
Glad you enjoyed it
@user-ig9hf2gc4j
@user-ig9hf2gc4j 2 місяці тому
Thank you very much for providing great content, Your videos are awesome.
@tundsdev
@tundsdev 2 місяці тому
Glad you enjoyed it 🤝
@Decatilinae
@Decatilinae Рік тому
Thanks for sharing. Happy new year 🎉
@tundsdev
@tundsdev Рік тому
Happy new year!
@user-do7dv4kd2g
@user-do7dv4kd2g Рік тому
great tutorial. For those who will try to do it from scratch with custom data: There is an Integer 16/32/64 type for @NSManaged property in core data as type of value and if you will assign an int value like age = 20 you will get an error - you should cast it to corresponding data type like age = Int16(20) .
@tundsdev
@tundsdev Рік тому
Thanks 🤝
@aliDevJourney
@aliDevJourney Рік тому
i really like your teaching styles, thanks!
@tundsdev
@tundsdev Рік тому
Thanks and glad you enjoy the content 👌🏾
@srome0711
@srome0711 Рік тому
Awesome video Tunds - Question, you mentioned adding another video that talks to relationships and using those. Is that out yet? am I missing it
@tundsdev
@tundsdev Рік тому
Thanks and nope its not out, it’ll be a video thats part of a paid course
@srome0711
@srome0711 Рік тому
@@tundsdev alright I got cash ready haha
@AppDeveloperPoint
@AppDeveloperPoint Рік тому
Great video man. You are definitely going to kill Udemy with these free courses. Appreciate your effort in making such quality content available free of cost 🙂
@tundsdev
@tundsdev Рік тому
Glad you enjoyed it 👌🏾
@anassalah838
@anassalah838 Рік тому
love it thk bro ^_^
@tundsdev
@tundsdev Рік тому
Glad you enjoyed it
@hadleyboy77
@hadleyboy77 Рік тому
Hi tunds, great video man I learnt so much from it, your teaching style is top class. I'm working on an app that has a store of airports. I was parsing them from a csv and storing them in an array but thought committing them to core data would be a faster way to handle them. is there a way to load a set of data, from a csv in the bundle, into core data on first initialisation?
@hadleyboy77
@hadleyboy77 Рік тому
Never mind I figured it out! Thanks for helping me develop the tools to work it out myself, what a legend
@tundsdev
@tundsdev Рік тому
Glad you figured this out also apple has a sample app called “Quakes” that shows you how to do this too
@Srijonlucky0111
@Srijonlucky0111 Рік тому
This is beyond awesome! I really love it. I already have completed few courses of you. Looking forward to complete more. However, I have little confusion regarding use of background context. In which cases I should use background context? Besides, need little more knowledge on concurrency of CoreData. By the way, love you man. Will try to support you soon.
@tundsdev
@tundsdev Рік тому
Thanks man, and background contexts basically allow you to make changes to the same object but on two different threads. The reason why you’d wanna do this is because you may want to edit an object on a separate screen but not automatically commit those changes (like we do with the edit view model) It’s a safer way to make & isolate changes to some kind of object, rather than just changing everything on the main context
@bjeber
@bjeber Рік тому
Thanks!
@bjeber
@bjeber Рік тому
Thanks for sharing this valuable video. have a great new year!
@tundsdev
@tundsdev Рік тому
No worries, hope you enjoy it 👌🏾
@bhanub1698
@bhanub1698 11 місяців тому
Amazing. Please make video on "How to work with Relationships in CoreData" also. If it is already available somewhere, pls share the link
@tundsdev
@tundsdev 11 місяців тому
Thanks & it’s coming soon 👀
@what4401
@what4401 Рік тому
thx
@tundsdev
@tundsdev Рік тому
No, thank you for watching 🫡
@WorkByTaylor
@WorkByTaylor Рік тому
Thanks for making this video man, it's been a huge help. Do you mind if I ask a question? What's the reason for including the delete function in the provider, and not the viewmodel?
@tundsdev
@tundsdev Рік тому
Great to hear, so that view model isn’t used to manage core data objects. It’s only purpose to act as a wrapper to help you either create or update a contact. The persistence manager has full responsibility of interacting with Core Data. The view model just acts as a helper for managing contacts 🤝 Hope that answers your question
@WorkByTaylor
@WorkByTaylor Рік тому
@@tundsdev Wow - that was quick! Thanks Tunds, that does help. I've used this project as a starting point for my own app, and I think your comment could explain some of the glitches I'm seeing. I'm going to move some functions over to the provider to see if that helps.
@tundsdev
@tundsdev Рік тому
The sample code is on my GitHub also if you want to tweak it for your needs too 🤝
@WorkByTaylor
@WorkByTaylor Рік тому
@@tundsdev Thanks - I had a look at it after I finished the video. You explain things so well, that the code-along I find is better for my own learning and understanding.
@hiassea
@hiassea 19 годин тому
hey @tundsdev, I hope you get this. I am a swift developer and I've been racking my head around how and WHERE/WHEN to persist data. The former was solved in this video while the latter still bothers me. My question is do I need to persist the user data or like an array of datas gotten from the API or don't I need to persist. PLEASE HELP
@ridholmes
@ridholmes 11 місяців тому
Tunds, could you please explain the reason NavigationBar background 'blinking' at 2:04:26?
@tundsdev
@tundsdev 11 місяців тому
Thats just how it reacts when you tap cancel and exit the search bar, its just a system thing
@taothetaoist-6166
@taothetaoist-6166 Рік тому
cool.
@tundsdev
@tundsdev Рік тому
Hope you enjoy the vid 🤝
@ssaai
@ssaai Рік тому
Happy New Year
@tundsdev
@tundsdev Рік тому
Happy new year
@ridholmes
@ridholmes Рік тому
Yo, Tunds, thanks a lot, bro. Thank you very much for your time spending on all your tutorials! While watching this one, I encountered a problem, and I really hope you can give me a hint, and then I'll figure it out. Suppose, in addition to the 'Contact' entity, I also have a 'Country' entity in 'CoreData'. And in addition to entering name, email, etc., the user also selects his country. At the moment when we retrieve all countries from the main context and try to assign the 'Country' from the main '.viewContext' to Contact.userResidence in '.newBackgroundContext()', a problem arises. I think you understand what I'm talking about. What approach should I use to solve this problem?
@tundsdev
@tundsdev Рік тому
Hi Rid, Glad you enjoyed the vid. This was meant to be simple and not work with relationships. I actually have a paid course i’m working in that will follow simple & complex relationships when working with CoreData so make sure you’re subbed & follow me on twitter for updates
@ridholmes
@ridholmes Рік тому
@@tundsdev I understand what you're saying. Unfortunately, I can't take a break and wait for the paid courses to come out, so I have to find a solution here and now. And I've found it. Anyway, thanks again for all your tutorials - they're very helpful! I'm grateful to you for that, bro!
@ridholmes
@ridholmes Рік тому
For those who are reading the comments, I did the following: 1. Added @Published var selectedCountry: Country? in EditViewModel() 2. Wrote a function updateResidence(for selectedCountry: Country?) where I create a new variable if let backgroundCountry = try context.existingObject(with: selectedCountry.objectID) as? Country {...} 3. Here {...} assigns seller.residence = backgroundCountry You need to use do-catch and unwrap the optional selectedCountry before the do-catch block.
@ridholmes
@ridholmes Рік тому
@@tundsdev Bro, don't judge me harshly, some people in the comments asked the same question) I just gave one of the possible solutions to my specific problem, and it may not work for everyone.
@tundsdev
@tundsdev Рік тому
Awesome thanks for sharing this solution. Whilst I work on this course. We're all in this together 🤝
@wilfredlalonde9760
@wilfredlalonde9760 Рік тому
Hi Tunds! I'd like to default the first view to Favourites. I'm having trouble with the line "@FetchRequest(fetchRequest: Contact.filter(with config: SearchConfig ... etc. Looking for your wisdom, my friend. Just setting the filterType to an initial value of .fave didn't work. Many thanks!
@tundsdev
@tundsdev Рік тому
Hey man, so you’d have to create a fave func version of the Contact.all() that gets passed into the fetch request. That way be default if would be fetching favourites. Best of luck you got this 🤝
@WilfClegg
@WilfClegg Рік тому
Ok, I can do that…didn’t think it. Thanks for your quick reply, Tunds! I’ll send you a copy of my version of the app (I added a few things) 👍
@tundsdev
@tundsdev Рік тому
All good my man 🤝
@alexandrelemarchand4029
@alexandrelemarchand4029 Рік тому
Hey Tunds! I'm sorry to bother you but I have a lil problem with my application. When I (successfully) edit my CoreData file, the UI doesn't change and I have to quit the application and come back. I am using the same sheet modifier and the same "...ToEdit" variable as you. I also want to thank you for sharing your knowledge with all of us! Have a great day and thanks in advance for the answer!
@tundsdev
@tundsdev Рік тому
Hey in the description box i have the source code so you can compare the final solution, since I can’t guarentee what you’ve done. You can compare my final code & app with yours to see the difference 🤝
@andrewmuniz5283
@andrewmuniz5283 10 місяців тому
In the Unit test section when I click run on the testContactIsEmpty function is passes the test but I keep getting the error "Cannot load underlying module for XCTest"
@tundsdev
@tundsdev 10 місяців тому
Make sure the unit test file is only added to the testing target 👌🏾
@ridholmes
@ridholmes 11 місяців тому
And here is another question: XCode, when creating new project with CoreData preinstalled configuration, by default creates a struct PersistenceController, what is the reason Apple preinstalls struct, but not a class, like you did in your project?
@tundsdev
@tundsdev 11 місяців тому
Its just a quick start to help you get running quickly, I used a class rather than a struct so I can have a singleton and only 1 instance of my persistence container. If you use a struct you’d be recreating it every time you want to use which I don’t want to do. I just want to load it once it memory and use it during the lifetime of my app
@nroose
@nroose 4 місяці тому
I really think they should have called "entity" "table" and "attribute" "column". In the, uh, context, of conceptual modeling, entities and attributes are useful for that discussion. But these entities and attributes don't actually mean concepts as broad as that, and those names are conceptually too broad for the context of CoreData.
@srome0711
@srome0711 Рік тому
Anyone have suggestions on implementing adding relationships with this VM setup?
@tundsdev
@tundsdev Рік тому
Hey, so this was more of an introductory video on implementing CRUD. Adding relationships would only make it longer 😅 Just to keep you in the loop i’m planning a paid core data course that features relationships, optimisations and more. I’m not too sure what your code looks like, so i cant make a suggestion since this view model is more just a simple starter with Core Data
@srome0711
@srome0711 Рік тому
@@tundsdev No worries - Got a person tutor, Chat GPT haha. Ill keep a lookout for that course though
@johnpill1
@johnpill1 Рік тому
Hey Tundsdev. I've managed to get my first app working with Core Data and SwiftUI. It works on software sim and my phone. However I get the following error. Do you know what causes it? Should I be worried? pocketMoneyPics is the name of the core data file, Present is the Entity name. CoreData: error: +[pocketMoneyPics.Present entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
@tundsdev
@tundsdev Рік тому
Hey man I would try to resolve this warning for sure, we don’t get this warning in the vid since we only load the store with its entities once cos our persistence manager is a singleton. You may wanna look at this vid and see what you can lift into your own personal app, best of luck you got this 👌🏾
@johnpill1
@johnpill1 Рік тому
Sorry, its not an error, but a warning as the app is running and working. warning: Multiple NSEntityDescriptions claim the NSManagedObject subclass 'pocketMoneyPics.Present' so +entity is unable to disambiguate. I've tried changing the code gen to manual but this causes actual errors.
@tundsdev
@tundsdev Рік тому
@@johnpill1 Yep I know it’s a warning, pretty annoying one too 😅 A few things, make sure your persistance manager only has a single instance either being a singleton or a static var, make sure your model is set to manual & use current module as the namespace too from the drop down 👌🏾
@johnpill1
@johnpill1 Рік тому
@@tundsdev thanks. I think need to watch your video again. I think I’ve messed up what you refer to here as I was getting this to work with SwiftUIs new photo picker and storing and retrieving the images as Data, and converting them back and forth to save and use.
@johnpill1
@johnpill1 Рік тому
@@tundsdev Thanks Tundsdev I finally fixed this warning. I ended up downloading your source code and going through mine changing little bits so it operates the same. I am not exactly sure what was causing the error. But what I noticed is that I was accessing my DataController class directly (yours is called ContactsProvider). I added the shared technique and added this to my content view then changed all my buttons etc to access the content view var dataController = DataContoller.shared and the error stopped!
@ridholmes
@ridholmes 11 місяців тому
I can't understand one thing... When you edit a Contact, you create an entirely new blank Contact 'contactToEdit = empty (context: provider.newContext)', and then in .sheet, you pass it to CreateContactView(vm: .init(provider: provider, contact: contact)). I mean, there won't be a case where you create a vm: .init(provider: provider) with no Contact at all. Yes, you check it with .objectID (and in that case, it returns and goes to the 'else' block), but in my case, when I enable 'Swift Error' breakpoints, it always stops at that line and says: "yes, there is a Contact, but I can't find it, or something...". If I disable breakpoints, it works well, but every time you create a model, it always receives an empty Contact, although it could have not received one. The problem is that somehow I must change the contactToEdit value in order to trigger .sheet, but maybe there is another approach that could handle this collision?
@ridholmes
@ridholmes 11 місяців тому
I mean, when creating a new Contact, the ViewModel always receives an empty Contact, and then (when it can't find one with the objectID) just discards it and creates a new one in the 'else' block anyway.
@ridholmes
@ridholmes 11 місяців тому
For now, I created a dummy function, that just explore that contact, and if it is new - changes it to nil, and put it in CreateContactView(vm: ...), but that's some kind of madness...
@tundsdev
@tundsdev 11 місяців тому
👋🏾 When editing a contact, I don’t pass in an empty contact. I pass in the contact within the foreach closure block. The only time i pass in an empty contact is when you tap the plus button. If you look at the edit swipe action, you’ll see that I don’t pass in an empty contact Unless i’m misunderstanding your point. You can see an example below. github.com/tunds/youtube-content-2023/blob/main/Quickly%20and%20Easily%20Implement%20Core%20Data%20in%20SwiftUI%20%7C%20Free%20SwiftUI%20Core%20Data%20(CRUD)%20Course/MyRideOrDies/MyRideOrDies/ContentView.swift
@ridholmes
@ridholmes 11 місяців тому
@@tundsdev Excuse me, I wrote that wrong. I meant when you Create a new contact, not edit. When you create am empty contact, you pass that empty contact to VM, but VM discards it (when looking at it's .objectID) and create another new one. My question was how should I call that .sheet without passing an empty contact (other words: with passing nil, so VM anyway would create another empty contact for me in the 'else' block), when I create a new one. Because VM can handle a 'nil' situation, and it will create a new contact.
@tundsdev
@tundsdev 11 місяців тому
I’m currently away on hols atm, so i’m not able to check but i’m pretty sure there is a reason why I did it like this, (passing in nil doesn’t trigger the sheet I feel)
iOS Core Data QuickStart Tutorial 2020
1:10:58
CodeWithChris
Переглядів 97 тис.
Donny Wals: Using Core Data in a Modern SwiftUI Application
41:18
Swift Heroes
Переглядів 13 тис.
Зомби Апокалипсис  часть 1 🤯#shorts
00:29
INNA SERG
Переглядів 3,8 млн
Learn the Essentials of Swift in one hour
58:14
Paul Hudson
Переглядів 164 тис.
MVVM vs. MVI - Understand the Difference Once and for All
18:40
Philipp Lackner
Переглядів 21 тис.
CoreData в Swift. Разработка приложений
47:55
simpleDEV. Swift c нуля до бесконечности
Переглядів 7 тис.
ViewModels & Configuration Changes - Android Basics 2023
18:46
Philipp Lackner
Переглядів 90 тис.
Fetching Data in React - Complete Tutorial
29:10
Cosden Solutions
Переглядів 70 тис.
Core Data Tutorial - Lesson 1: Core Data Basics
6:47
CodeWithChris
Переглядів 63 тис.