SwiftUI 2.0: Core Data - How To Use Core Data From Scratch (2020)
Вставка
- Опубліковано 11 вер 2024
- In this tutorial you will learn how to use Core Data with SwiftUI 2.0 from scratch. First you learn about Core Data and its Core Data Stack, then you learn how to create a basic app with CRUD (= Create, Read, Update and Delete) capabilities using SwiftUI and Core Data.
Any idea why the "preview/canvas" doesn't run? We have to run it in the simulator. Is it an Xcode bug?
Good question! It is not an Xcode bug. The preview relies on the "ContentView_Previews" and not the "ContentView". We have to set the managedObjectContext environment for the "ContentView_Previews" as well. So you could simply add: ".environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)" after the "ContentView()" in "ContentView_Previews". That should fix your problem.
In practice this is quite nice because it also allows you to use a different viewContext for previews if you want.
@@BeyondOnesAndZeros Thank you!
@BeyondOnesAndZeros its odd, I added the code by copying and pasting it into "Contview.swift" in "ContentView_Previews" under "ContentView()", I am getting an error "Cannot PresistenceController in Scope"? I can see that exact in "ToDosListApp". What I am not getting here?
Never mind, don't wast your time... I should read more thoroughly... I was putting the code below "ContentView()" instead of after it.
@@khram84 You're right, it should go right after it. Glad you sorted it out! :)
This was a great video. I've been trying to find Core Data tutorials, but most of the ones out now are based on Xcode 11.x and earlier, with App and Scene delegate files. Your video was the first I found that used the new SwiftUI lifecycle and implemented the stack with Persistence.swift. Thanks!
Thanks Kenneth, good to hear that! :)
I've followed at least 10 tutorials on SwiftUI and Core Data. This is the first tutorial that showed me how to do an "update". None of the other videos included the update function for Core Data. Thank you, well done...and excellent explanations throughout the tutorial! Now I will take what you have taught me, and reformat it into an MVVM structured xCode framework. Beautiful!
I've watched 3 to 4 Core Data tutorials, and this is the most and only clear one. Thank you and please keep making these high-quality tutorials.
Your deserve way more subscribers, thanks for continuing to publish these great videos!
Thank you, Joe! Good to hear that these videos are helpful. I really appreciate the support :)
BeyondOnesAndZeros 100% agree with Joe. Hope we can help spread the word!
This is fantastic tutorial! Would you please create one with MVVM + Core Data as well ? Thanks a ton again! 👏🏻👏🏻👏🏻
OMG thank you so much for this nice tutorial!
All other tutorials i found were either too old or just way to complicated - but yours is just perfekt!
Have some cookies for your nice efforts 🍪🍪🍪
Bro, I'm in love with your tutorials. Whenever I see that you made a tutorial for the topic which I'm looking for, I feel amazing because you explained everything very well. Keep going!
Thanks Batuhan, glad you find them helpful! appreciate the support :)
This is the best tutorial that I found in YT, thanks!
Very helpful and well planned, many thanks!
I've watched other core data videos. Your explanation is 100% better than all of them.
Thank you for doing such a great video.
Thanks Bill, great to hear that!
I have been following you for awhile and you have contributed allot for your viewers. I count myself lucky to be able to learn from your tutorials. One course you should think about would be JSON to Core Data.
Hi Robert, I appreciate your support! I have a question regarding your request.. are you suggesting a tutorial on loading a JSON from the web and storing it on the client as some kind of caching mechanism?
Finally got round to watching this - very nice summary! Thank you.
Thank you, James!
Thaaaankss!! Brilliant tutorial for work DB + UI, amazing work)
Great tutorials! Much appreciated. I will let the communities be aware of your Channel.
Wow, thank you! I appreciate the support :)
Thanks for the through explanation and demoing. It was the first time I watched your video and I'm immediately sold 🙂 Going to watch other videos of yours. If it's not much to ask though can you use the dark theme?
Thanks! Links to the code on github or another repository would be appreciated. (mainly for notes because sometimes screen didn’t show entire file content). Thanks in advance for editing the description to post that code.
Thank you very much for such a simple explanation!
Thank you so much... Go Beyond
Thank you so much for clear and concise explaination on SwiftUI 2.0 core data!
Thank you , this is way more easier and less code than using property list to make a crud list app.
I stand corrected (and helped!)... This works! Great video.
Thanks for this great tutorial! Covered all the basics in a clear and understandable way. Would love to see how this can be adapted to work with CloudKit!
Thanks, Jeff! Good suggestion, it's already on my list. I will get to it as soon as possible :)
Hi Jeff, I finally got around to create the video on CloudKit: ua-cam.com/video/F5B6fbTAl04/v-deo.html enjoy :)
@@BeyondOnesAndZeros Thank you! Checking it out now...
This was great. Maybe update for Xcode 13 and show a products based model, say for invoicing... just an idea.
Excellent tutorial, thanks
Concisely explained. Well done!!
Thanks Abolina!
Great tutorial! The logics though need to be inside a ViewModel
Phenomenal tutorial! Thank you so much for your work on this.
Great to hear that Quinn, you’re welcome! :)
Thanks for the awesome content!
What an amazing tutorial!!! Much appreciated. I had one question. Is it possible to test this on a live iOS device? When I switch the simulator to my actual device it complains about Task not being in scope. Is this a bug or can you not test core data application on a live device?
A great help. Thanks
why does fetchresults does not require ViewContext but Contructor of Task in addTask does require one ?
great work.. its very simple. Thanks..
Thanks, Kasi! :)
The app builds then crashes. it seems that the database is empty and possibly the pointer is negative to start.
Fatal error: Unresolved error: nil: file CoreData2/Persistence.swift, line 18
2021-03-20 14:52:50.860348-0700 CoreData2[42026:4013387] Fatal error: Unresolved error: nil: file CoreData2/Persistence.swift, line 18
(lldb).
Line 18 is this : if let error = error as? NSError? { fatalError("Unresolved error: \(error)")}
Am I missing something? I have spent an hour on this, and gone over the video twice to make sure its precisely the same (AFAIK)
Thank you !! However, NSManagedObject is a class rather than a protocol , right ?
Shutting down and launching Xcode again doesn't solve the "Cannot find type 'Task' in scope" for me, don't you have any other tip please??
CoreData: error: +[Task entity] Failed to find a unique match for an NSEntityDescription to a managed object subclass
Fatal error: UnsafeRawBufferPointer with negative count: file Swift/UnsafeRawBufferPointer.swift, line 872
2021-03-02 18:01:01.704378-0800 ToDO[6139:143889] Fatal error: UnsafeRawBufferPointer with negative count: file Swift/UnsafeRawBufferPointer.swift, line 872
I get this error above and not sure why. You have any idea?
Great tutorial, this helped me a ton - thank you so much!
I have one question though: I want to move all the CRUD functions for the tasks into a TaskManager class because I want to keep my views as clean as possible. This works great, except for the part about updating.
My method inside the TaskManager class is func update(_ shoppingItem: FetchedResults.Element, withTitle title: String) and I'm getting the error "Cannot find type 'FetchedResults' in scope". Any hints as to what I am missing? Passing the Task using the method call from the view does not seem to do the trick...
If I wanted to do a MVVM architecture, would I put the...
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [])
@Published var list: FetchedResults
in the ViewModel??
Great Explanation👍
Thank you! :)
At 13:40 xcode did not want to work with .environment. I had to restart xcode fresh and it all runs now. Maybe someone else has this issue...
HELP I am getting this error message CoreDataNSManagedObject must have valid NSEntityDescription. What should I do i am a beginner! Thanks 🙏
Great!!!!
Insane buddy. Thanks a lot
Fine, thank you!
Hi, thanks for this tutorial.
I have an question, how to move fetch from core data into model?
Hi, thanks for tutorial. How much record can be saved in Core data? It is suitable for large databases with thousands records?
How to delete all tasks in one time? ^^ thank you
Thanks a lot
How would we have it so we can customize the tasks with a textfield?
Sztosiwo! thx!
Excellent tutorial! Very clearly explained.
Could you use a Dark Theme for Xcode such as Midnight?
Thank you, Drayton! Sure, I will consider the dark theme for future videos :)
@@BeyondOnesAndZeros Looking forward to it!
I use a Post NSManagedObject class for some posts.. i use that post class for my main Feed View, for my Favorites View and my Profile View... how do i only save the Posts that use in my profile view. Do i need a separate context? A separate container? Maybe a coordinator? Can someone help me on this one
I have two entities with a `Position` entity having a "to-many" relationship to an `Order` entity. I'm assuming I'd need to use an NSPredicate to filter the orders fetched by the matching position? I know the position entity has a property of type orders but it doesn't seem that accessing that property allows for smoother, natural animation like the fetch request process does. Would you be willing to create a video using relationships in CoreData and using NSPredicates?
Hi there, that’s an interesting example. I will cover entity relationships in more depth in a separate video maybe it will help you to solve your problem.
Nice tutorial. Thanks
Thanks, Aleksei!
how do you know all of these stuffs ?
Brilliant .. great work indeed and thank you !... any chance of adding to your code, so that the user can add some text etc.. and also... incorporate iCloud too ? Thanks... Craig.
Thanks, Craig! That’s a great idea, I will cover these topics very soon in a follow up video.
fyi. there is now a video on CloudKit that covers the part on how to incorporate iCloud: ua-cam.com/video/F5B6fbTAl04/v-deo.html
Do you have any source code repositories for your examples?
Hi Michael, as of now I do not have a repo for my examples. But I will try to set one up and will get back to you
@@BeyondOnesAndZeros any luck?
How do you go in line 18 from 11:39 state (with the text "completionHandler") to the 11:41 state (without "completionHandler", but with "in code") ? A cut in the video? A shortcut? Where is the explanation, please?
Hi quark67000, it’s a nice and handy Xcode auto completion feature. You access the auto completion by highlighting the spot that you want to “auto-complete” using the “Tab” keyboard key, and pressing the “return” keyboard key to replace the placeholder with the suggested auto-completion.
@@BeyondOnesAndZeros Thanks very much, I wasn't aware of this feature! Great!
@@quark67000 You're welcome :)
Hi ,
My app is so slow when launching, and it says that is more than 40 tasks , how can i fix this?
Hi Thuraya, are your launching your app on the simulator or a real device? Also it would be interesting to know the specs of your hardware that runs Xcode. Nevertheless, the simple code in this example should not lead to any crucial performance bottleneck.
I have this error in Xcode12:
RemoteHumanReadableError: Failed to update preview.
The preview process appears to have crashed.
Error encountered when sending 'previewInstances' message to agent.
==================================
| RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)
|
| BSServiceConnectionErrorDomain (3):
| ==BSErrorCodeDescription: OperationFailed
Hi, please see the answer to the pinned comment. You should be able to solve this by simply setting the environmentObject to the preview.
@@BeyondOnesAndZeros I already have it, but still failed:
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
.environment(\.managedObjectContext, PersistenceController.shared.container.viewContext)
}
}
This seems to be a common issue with the new Xcode version. Did you add anything on top of what was shown in the video? Feel free to send me your project and I will check if it compiles on mine :)
Hi,
Is it okay to have more than one big array (not json) of texts , colors , or images in my app(because i write it my own ) , and if not with what i can replace it?
Thanks.
Hi Thuraya,
Can you give me an example of what you are trying to achieve? Do you mean by writing “your own”, your own custom types?
I'm made an array that has more than 100 questions , and i wrote these questions my self.
It depends. If you have an app where you as the user create the questions using the app, it is totally fine. However, if you are creating these questions in code, it would be much more maintainable if you would load these initial questions from a JSON.
Thank you 🙏
You’re welcome :)
Sorry but I have this error: [error] error: Failed to load model named TodoList
I solved, I insert the wrong name in NSPersistenceContainer arguments. Great guide
Awesome, glad you figured it out! :)
Where can i find the (App.swift ), the file with the @main keyword ?
Hi Thuraya, it’s part of the new Xcode Template. Create a new Xcode project and choose “App”, and in the next screen where you define the project name make sure to set the “Life Cycle” to “SwiftUI App”. If you do not see the option you’re probably running an older version of Xcode.
yeah, I think you're still using the appDelegate method
👍🏼👍🏼👍🏼
why you don't have unlike woow 😍😂
Haha thanks Sipan, appreciate the support 👍
hey very good instructions. it doesn't work for me can i send you my code?
Thanks Sebastian. Sure, drop me a mail at beyondonesandzeros[at]gmail[dot]com
Hi Sebastian, I had a look and found out where your issue is. You are calling the ".navigationTitle("Todo List")" and ".navigationBarItems(trailing: Button("Add Taskt").." on the NavigationView but it should be called on the ending curly bracket of the List instead. That should fix your problem, give it a try and let me know :)
@@BeyondOnesAndZeros Hey Beyond, it works :-) Thank you very much
@@SebastiansBlog23 Awesome! you're welcome :)
This didn't work...
Hi Brett, do you mind sharing where you’re stuck and what error message you are getting?
@@BeyondOnesAndZeros As soon as I build the project, it launches the simulator and crashes with an error "container.loadPersistentStores { (storeDescription, error)... Right around the 20 minute mark in the video if you are following along.
Your Xcode logs should show sth after: "Unresolved error: ". That’s the interesting part, that could help us to find the issue. Feel free to send me your current project and I will have a look at it :) beyondonesandzeros at gmail dot com
@@BeyondOnesAndZeros That's amazing. I will send it to you and really appreciate your quick response and help! It's a great video and I was frustrated to hit the wall.
@@thebrettlarson I had a look at your source code. The issue is in the errorHandling of your PersistenceController.swift file. Please replace: "if let error = error as? NSError?" with "if let error = error as NSError?". Your current definition basically holds always true and throws a fatal error, even if everything is fine :) I hope this fixes your problem, if not let me know and I will have another look.