Core Data with SwiftUI (Create, Read, Update and Delete)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to adam sharp weekly and in this video i'm going to show you that how you can get started with core data with surf ui now this is going to be a little bit longer video because i'm going to show you how you can set up the core data how you can perform create operation delete operation update operation and read operation for a very simple sieve ui application this is actually part of my course the new course that i'm working on and it the course will be available in the future i don't really have any date associated with it right now just started working on the course so this part is actually part of the course and whenever the course is released i well you'll know because i'll uh talk about it in my youtube videos so let's go ahead and get started i'm going to go ahead and create a new xcode project and the app is perfectly fine let's just call this hello core data make sure you are selecting safe ui and also make sure that this is not check marked meaning that we are going to set up core data on our own let's do next location is fine let's go ahead and create the app perfect let's check out our preview which is not really going to show much it's just going to show the iphone with hello world written on it and let's go ahead and change this to iphone 12 pro max all right now the reason that we didn't check mark use core data is we want to set up core data on our own and that's the main reason so let's go ahead and get started with setting up core data the first thing we need to add is the model file associated with the core data so i can go to the project and i can add a new file and if you scroll down you're going to see core data and data model and that's the that's the file that we want to add the data model file so let's go ahead and select that you can name your data model anything you want i'm just going to go with hello core data model kind of like going with the name of the app itself let's go ahead and create that okay so our data model is created the whole point of the data model is to declare entities to declare relationships and to basically say that this is kind of like the graph that core data will be using core data itself is not really a database it's basically a framework that can map a tree into or a hierarchy of data or a relationship into persistent storage which can be a database which can be an xml file which can be binary file which can be something else but core data in itself is not really a database but yes in the end it does or it can persist to a database okay so right now we don't have any entities meaning we don't really have any model we don't have anything to persist in core data let's go and go ahead and click on add entity and you can see that in the entities now we have well an entity called entity that's a horrible name for a model so let's go ahead and change this to movie right over here you can define different attributes for the movie meaning the title of the movie the director the actors whatever attributes or properties are associated with the movie so i'm just going to go ahead and add one attribute only which is title which is the title of the movie the type will be string that's fine now if you want to check out more properties of this particular attribute go ahead and click over here and when the attribute is selected you can see all the different properties of that attribute now by default it is actually saying that the title property the value of the title property is optional and i don't really want it to be optional because well title is required to persist to save a movie so that's make sure that this is unchecked now if you click on the entity which is over here itself the menu obviously changes and it has a couple of different information the most important part is the class name that is generated which is right here which is going to be called movie and how the code generation tool will generate that particular entity so you can see that it's saying class definition which means that the core data is going to be responsible for writing or for creating the movie model for you but there are some other options also you can see that there is manual or now none which means that you are responsible for writing that particular model there is also category extension which is which means that it will create an extension for that particular model um so you can see it has a different things i'm just going to say class definition which means that core data will be responsible for creating the model for me all right so this is all good let's go ahead and build our app great now the model file is ready this is great what we want to do is we want to create some sort of a manager or provider so that we can load this particular file and load all the models so that we can initialize our core data so i'm going to go ahead and add a new file over here i'm just going to add a group i'm just going to call it managers and in the managers i'm going to go ahead and add another file and i will call it core data manager the whole point of core data manager is to manage core data to initialize score data to update a particular movie to retrieve a movie to delete a movie and all those kind of operations all right the first thing i'm going to do is import core data so let's go ahead and import the coordinator framework now i'm going to go ahead and create core data manager and in the core data manager i'm going to go ahead and create an instance of something called a persistent container now what exactly is this ns persistent container ns persistent container is basically responsible it's more like a top level class and it's responsible for initializing your core data stack it's it's basically responsible for loading the model and then all the different stores associated with the model and this was introduced in xcode 10 and above i don't know if you remember but when you had to initialize core data a long time ago you had to write like a lot of lines of code but now with ns persistent container you can initialize core data with much less code let's go ahead and implement the init function for the core data manager inside the init function we are going to go ahead and initialize ns persistent container we're going to pass in the name and the name in this case is the name of the model that we have created so core data model which is actually right here okay that's great the next thing we need to do is we need to load all the persistent stores this means that whatever whatever stores that we are subscribed to whatever store that we need it's going to load that particular store by default the store is actually a sql lite store this means that when it is going to save the data it's going to save the data into sqlite which is a relational database description and error if we go ahead and get an error we're going to unwrap the error and at this point if we cannot even load that we can go ahead and simply say core data store failed i mean there's no point moving forward and there's literally nothing we can do at this point all right let's go ahead and build that okay so we have created code data manager and if we initialize it it's going to allow us to initialize the core data stack which is great the next thing we need to implement is how to save a movie so i'm going to go ahead and create a function called same movie you're going to pass in the title of the movie that you want to save that's the name of the movie and remember when we created the entity over here called movie we need to create an instance of the movie entity the movie class so that we can persist at entity through core data to our sqlite database so let's go ahead and create movie and you can see movie in order to create the movie we have to pass in the context and we can use persistent store container dot view context now the view context is a access to the context which is on the main channel or basically the main thread so you can simply use your ui to persist these things i mean it's it's so it's not on the background thread it's on up to available on the main thread now right now in this particular video i'm not going to use the mvvm model or some sort of a view controller model with ourself ui app we're just going to allow our core data to be accessible from the view which is completely wrong and you should not do that but we're just trying to get hang of core data later on we will introduce mvvm so we can use it over there we're going to go ahead and set the title which whatever you passed in and now we can go ahead and simply call persistent container dot view context dot save so this means that every single thing in the view context is going to be saved now this method save can actually blow up so we will make sure that we're calling it with try and whenever there is an exception we can go ahead and say fail to save movie and we can also you know display the error all right this is great now we can actually move on to our other side which means our view and we can see that how we can use our view to save the result or save the movie so this is what our view kind of looks like and you can see it's not really much going on with the views so what i'm going to do is i'm going to go ahead and first of all create a navigation view inside the navigation view i'm going to go ahead and create a stack vstack and inside the vstack i can go ahead and create let's say enter title and i think for the text i think that's the another property name right and we will let's go ahead and say movie title make sure that we have some sort of a state so private war movie title and we will initialize it with nothing so this means that whenever we type something in the text field it is automatically going to go to the movie title all right i apologize it's actually raining in the background and it's raining ice or sleet so you might be hearing that sound okay so we're in the v stack let's go ahead and give a little bit of padding this is not really about the ui so i'm not going to mess around with the ui too much let's go ahead and also see if we can add like a navigation title or something and we'll just call it movies maybe i added the wrong place let's see over here navigation title over here and let's go to movies there we go okay so we have the text field but we don't really have a button so let's go ahead and add a button also which is to save a movie and let's go ahead and add a spacer so everything is kind of like pushed to the top okay that's fine we can use a text field different style so text field style will be let's say rounded border text field style okay that's uh that's perfect i mean we're not doing any ui stuff so that's perfectly fine the next thing we need to do is we need to use or we need to initialize core data manager so i'm going to go ahead and create an instance of core data manager on the top as soon as i do that the xcode preview is going to complain because now i need to pass in the core data manager right over here so let's go ahead and do that core data manager core data manager and like this and we also have to make sure that the app point which is this one that we are sending in the core data manager so code data manager so that whenever we initialize it we have the core data manager let's go back to our content view and inside the save function now we can go ahead and say core data manager dot save movie and then pass in the movie title now once again please do not do this do not call your core data manager from inside the view the only reason i'm doing that is just to show you how to kind of like get started with core data but in an actual app you should create some sort of a view model layer and you should use or call core data from the view viewmodel layer instead of from the ui alright so that's actually pretty good and that will allow us to save a movie let's go ahead and run this now we may be able to save a movie but we are currently not displaying the movie so let me go ahead and click save and it does nothing all right so we need to get the movies also and then possibly display it over here so let's go to code data manager just like the save function we're going to go ahead and create a function called get all movies and it is returning you it will return you an array of movies now the question is well how do we get all the movies now in core data when you need to get something or fetch something using core data you use ns fetch request so let's go ahead and create a fetch request which is of type ns fetch request but we will make it typed meaning that we're going to tell it that this is what we're trying to fetch and the good thing about the movies that we can call movie.fetchrequest and it will give us the instance of the fetch request now we can go ahead and perform the question request using persistentcontainer.viewcontext.fetch and passing in the fetch request and this is going to return us at the array of movies which we can basically go ahead and return now if this blows up then well we can return nothing you can return kind of like empty array all right so with this in place now let's go back to our content view and see that if we can go ahead and load the movies so when this is loaded let's see where we can do that on up here we can say core data manager dot get all the movies now if it's returning you or getting all the movies it's returning you something right array of movies which is not really going anywhere so what i'm going to do i'm going to go ahead and create a state over here and i'm going to write over here also that not a good idea to use state to populate data from third party call third party or you know populator populate the data from core data i mean this has to be more of the view model thing and state is not really used for that so i'm just writing it over here so that you know that putting the movies or putting some of these kind of things like actual data is not a good practice when you are putting it in a state variable state variable is mainly used for controlling the ui and making sure that your user interface is in sync with the data but since we're simply learning core data it's fine to use it this way for now now i can go ahead and assign it to movies and since the movies is marked with state and whenever you assign the state it's going to re-render the body so it is at that time that we can go ahead and print something or create a list so i can go ahead and create a list i can say movies and id will be self which is a movie object itself and movie in and then we can try to display the movie title so movie dot title so let's see that if that allows us to see something now one of the things you will notice over here is it we do have the title property but if you look at the bottom the title property even though in core data you said that the title property will be non-optional it's not an optional so it has to be string but core data created this movie entity for you a movie class for you which is actually which does have string or a title but it is that string optional now this might be a little bit confusing even though it is string optional or optional string if you try to save it to core data and do not provide the title it will complain all right so it's just when the class is created it marks it with optional string why does it do that i don't know why does it do that i think it has something to do with the compatibility with objective c and all that stuff so basically we have to unwrap it so there we go i can unwrap it let's go ahead and build it so that we know that there's no error and there we go i don't know when i entered this qqq maybe it's reading it from somewhere else also okay so we got these two data so you can see it's displaying uh let's go ahead and run this and add another one i'm just going to go ahead and say maybe batman save when i do save it doesn't really update but if i stop and run it again then you can see batman is added so this means that whenever we save it would be a good idea to well populate the movies again or get the movies again for that let's go ahead and create another function populate movies so that we don't have to type this code again and again we can copy this code put it over here and on the on appear we can simply call populate movies and now whenever we are done saving which is over here we can add another line where we can say populate movies so right after saving it's going to go and fetch the movies again okay so let's go ahead and run this again and we have spiderman batman let's go ahead and add superman and here we go let's add another movie if you want let's say lord of the rings boom great so we were able to do a couple of different things over here we were able to display the movies we were able to save the movies but now the next thing is that well okay how do i delete the movies now in order to delete we have many different routes but i'm going to go with swiping from right to left if we do a swipe right to left a delete button should appear which will allow me to delete the movie so let's go ahead and see how we can create that swipe so i'm going to use the same list but inside the list i'm going to run it for each loop and the 40s loop will look exactly like what we were passing in the list so i'm going to go ahead and pass in the cells and the movie will get the movie and it's going to return a view which will be a text view movie dot title and like this it's the same exact thing but the good thing about for each is that it does come with a function called on delete and on delete is going to give you an index set because you can delete multiple items so we can go ahead and iterate through these items we will get an index of a particular item that you want to delete and we will get a movie from the movies so that we know that which movie you're trying to delete and now we will delete it using core data manager which we have not implemented so let's go back to our code data manager and let's go ahead and see that how we can implement delete movie delete movie we're going to pass in the movie and in order to delete a movie we are still going to use persistent container.viewcontext.delete and pass in the movie which is our ms manage object now this itself is not really going to delete the movie this is just going to mark it for deletion so you have to still save your manager object context which means that you have to call persistentcontainer.viewcontext.save and this is going to allow you to save everything in the manage object context if there is some exception you can also go ahead and say that well i don't want to do anything now i want to just roll back so this is a good way to roll back simply calling view context or rollback which means all the different changes that happened in your core data have been rolled back or in your manage object context will be rollback now let's go back again and we do have a movie to delete now so core data manager dot delete movie passing in the movie and when you delete a movie it's gone but the ui has to be refreshed so once again we're going to call popular movies to refresh the ui let's go ahead and resume it let's run it okay so let's try to delete this movie which is qqq delete refresh everything is gone let's go ahead and stop it and start again just to make sure it's actually gone and now you are able to delete movies all from core data and core data is storing all the information in sqlite so you can see that how fast we were able to build these things provided that we don't really have any layers and we're writing not a good code but hey we're learning right i mean eventually we can move all of this stuff into view models and that will be discussed in my actual course okay so the next thing that we want to do is we want to go to the details screen of a movie and then we want to update the movie now this is a little bit of a long process because the first thing we need to do is we want the user to go to a detailed screen so let's go ahead and create a new detail screen i'm going to go ahead and add a new view stuff ui view and let's call it movie detail great and the movie detail you need to pass in a couple of things in movie detail obviously you need to pass in the movie that you want to update so movie and i believe you can say let over here we'll see all right if you are passing in a name or you want to write the name of the movie i mean in the delete movie or sorry in the movie detail you will have a text box where the movie name will be populated you can type something and then you can update it but before that let's go ahead and make sure that we are satisfying this condition so let's see that if we can create or pass in the detail object or the movie object so i'm going to go ahead and say movie equals to movie and let's say that if we can create a movie and simply pass it so that our xcode preview is happy and there we go it's happy now all right the next thing that we want to do over here in the detail let's go ahead and uh first make sure that we are looking at the screen we need to make sure that we have a vertical stack we need to make sure that we have a text field so that people can write the name of the movie and what we want to do is we want to go ahead and pop automatically populate it with some data and now we can go ahead and say movie name which is a state variable that we're going to be creating so i'm going to go ahead and create the state variable right here so whenever you type movie name it's going to go to that particular state variable you can make the text box style or the model style to be rounded there we go and the next thing we can do is we can add an update button which is actually going to perform an update and we will only update if the movie name is empty it's not empty movie.title not sorry move it or title movie name dot is empty it's not empty basically so we will go ahead and say movie.title equals to movie name and then core data manager now we don't really have a core data manager so this means that is another thing that we need to pass in all right so that is another thing that we need to pass so you can see that our architecture is not really good in this case and then we will call it update movie there is no update movie in core data manager but you will see that update movie is going to be really simple because that particular movie object is already part of the manage object context so if it's already part of the manage object context and you have changed something the only thing you need to do is to save the context and that is how that is how you will save everything in that manage object context okay now we can go back to our content view and we can make sure that we are passing in or we are going to the movie details screen the first thing i'm going to do is i'm going to go ahead and add a navigation link and i'm going to use the destination part destination in this case will be movie detail right so movie detail that's a new page that we created we're going to pass in the movie which is movie we're going to pass in the core data manager which is core data manager and for the label we're going to display the movie name like the one that we were doing before there we go this means that whenever we select the navigation link we will be taken to the movie details screen that's going to build it i don't know why it's giving any problem okay so we have a problem over here that we need to pass in the another argument which is the core data manager so core data manager equals to code data manager in an actual application you're not going to be passing in the core data manager from one view to the other screen you will put it somewhere in the global global thing which which can be a environment object let's go ahead and build that great go back to the content view let's go ahead and build that also and let's go ahead and try it again now so let's go ahead and refresh it let's see if it uh compiles sometime i've seen that there we go all right so let's run it i'm going to select spider-man spider-man is automatically populated and instead of spider-man i'm going to go ahead and change this to batman and update let's go back it still says spider-man let's go ahead and load it again and if you loaded the game you will see that it actually saves batman so it was updated but once you go back it didn't really work at that point all right even though you were calling populate movies now this can be related to that you call populate movies it fetched the movie and since the movies is an array which contains objects of classes it didn't really know that i need to re-render the view again so how do you fix this problem now the way that you fix this problem is more of a hack than a solution so let me show you what i'll do is i'll create a state variable and that state variable will call which will be called needs refresh so which is going to indicate that hey i need a refresh or not all right now that particular value or state variable needs refresh is going to be passed down to your movie detail so i'm going to go ahead and say it needs refresh and i'm going to be passing it down as a bindable property this means that the movie detail can actually change this and if the if the movie detail changes this property inside movie detail then our content view can get updated let's go to movie detail and first of all make sure that it is accepting the needs refresh so i'm going to go ahead and create a binding var needs refresh which is of type boolean i also have to satisfy our movie detail previews so i do need to pass in something for the last argument which is needs refresh i'm going to just simply pass in false as a constant value for binding now every time we are going to add a movie which or update a movie by calling update we are going to simply go ahead and say it needs refresh.toggle and every time we toggle this value is going to change and since this is a bindable property which was originally sent from the content view the content view gets refreshed let's go and see if that works let's go ahead and play it i'm going to say batman i'm going to change the batman to spider-man i'm going to go ahead and say update go back oh no it didn't update okay so it didn't really update so that is something that we need to figure out again all right so let's see what is going on over here so just by changing the needs refresh is not going to toggling it between true and false is not going to do anything what we actually want to do also is we want to make sure that we are using it so i'm going to go over to list style and just going to say over here first of all i'm going to set the list type to something else let's say a plain list style it just looks nicer and i'm going to go ahead and say accent color and this is kind of like a useless thing that we're doing that we are saying that if the needs refresh is true then accent color will be white or else it will be black the only reason that we're doing that so we end up using needs refresh somewhere right let's go ahead and run this again now i'm going to go to spiderman i'm going to change that to batman updated go back and now it's batman hope you have enjoyed this video if you want to support my channel then the best way would be to check out my courses i have a lot of courses on civ ui as well as flutter i just released a brand new course on flutter with firebase you can definitely check this one out i have other courses for rx swift as well as combine and also writing your clean code so make sure you check out all of these amazing courses and i'm sure that you are going to love it thank you so much for your continued support
Info
Channel: azamsharp
Views: 11,809
Rating: undefined out of 5
Keywords: swiftui, core data, swift language, ios development, swiftui core data
Id: _ui7pxU1rNI
Channel Id: undefined
Length: 34min 3sec (2043 seconds)
Published: Sun Feb 14 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.