Core Data in SwiftUI Using MVVM Design Pattern

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

This programmer has one of the best presentation voices!

That said, what do you think of his approach here? Pros / cons?

👍︎︎ 1 👤︎︎ u/Rillieux17 📅︎︎ Apr 22 2021 🗫︎ replies
Captions
hello everyone and welcome to adam sharp weekly couple of months ago i talked about building a core data app using swift ui and i covered the required credit operation which was create read update and delete in that particular video and i will link to that video also we covered really kind of like a basic stuff we didn't really use mvvm or any other architecture we simply were learning how quickly we can go ahead and use swift ui with core data by writing all of our code in our views which is fine if you're learning but if you're building a little bit bigger application medium to even like large size application usually it's a good idea to consider some sort of a design pattern and one of those design patterns when you are implementing surf ui applications is mvvm and in this video i'm going to cover that how you can create mvvm application using core data to create the same exact app so you can see that we are starting from the very beginning you have the core data nvm project which is the surf ui project right now we don't even have core data stuff it's not initialized nothing is going on so the first thing i'm going to do is going to go ahead and add a new file so file it perfectly fine and we will call it core data manager core data manager will be responsible for initializing core data for us so we'll go ahead and import core data right there core data perfect okay so in the core data manager since we are using ios 14 which is above ios 10 we can go ahead and create persistent if something is called persistent and i guess it's going to appear a persistent container which is of type ns persistent container and ns persistent container is actually going to allow us to create or to initialize easily core data now since this is a let property we should also have a in it and inside the init we can go ahead and initialize persistent container by the name of the actual model currently we don't really have the model so i'm going to go ahead and simply say task model or task app model whatever you want to call it let's go ahead and add the add that model new file and the model is right there the data model for core data this model will contain all of our entities so i'm just going to go ahead and say you know to do app model kind of like a very parent kind of a name for the whole app to do app model and there it is to do a model it doesn't really have any entities or anything right now we will go ahead and add that later on but let me go ahead and jump into our core data model and call this to do app model and now i can go ahead and call so now that we have created the persistent container i'm going to go ahead and call persistentcontainer dot load persistence stores and we're going to get the description uh this time we don't really care about the description because well that's the only store that we have and we'll also get the error if there is an error so we can do something like this then well this means that you were not able to initialize the core data stack and there is not much that you can do so what should we do at this point well we can go ahead and perform an error saying enable to initialize core data stack and we can even go ahead and inject the error right there so that a person will know what actually happened all right now code the manager what we want to do is only create one single instance of core data manager so this means that we are going to limit creating multiple instances so we're going to create a singleton for core data manager and we can go ahead and create a shared property so shared let's say static let shared and that shared property will be an instance of the core data manager so this means that whenever we want to access the code data manager or any of the functionality of the code data manager we will always have to use the shared property which will construct an instance using this function but this particular constructor since it is marked with private it is not available to the outside world so this is our code data manager that's great i think the next step for us would be to create some sort of a interface that will allow us to add a to-do list item before we go to the interface i'm going to go ahead and create a new group and since we're using the mvvm design pattern i'm going to use viewmodel folder inside the viewmodel i'm going to go ahead and add a new surf file and we will call it task list view model which will also allow us to add a new task there we go class task list view model we will go ahead and say observable object if we want to need it we'll see if we want an either or not the only thing we are interested in is the title of the task i'm just going to go ahead and say title so that means we can set the title of the task and we will have a new function called save which is going to allow us to save the task now we can go ahead and create this instance which is our view model inside our view state object private var and i will call it task list view model equals to and instance of task list view model and now i can go ahead and construct some sort of an interface so i'm going to go ahead and say vstack or vertical stack and with a text field i'm going to go ahead and say enter task name and in the binding we can go ahead and say task list viewmodel.title this means that every time we're going to write something in the text box it is going to automatically update our title property in the task list view model i'm going to also go ahead and although we don't really need a navigation bar or anything like that over here let's go ahead and make sure that we are adding a bit of a padding that doesn't look that weird and we can also add a text field style by calling it the rounded text field style i thought there was a rounded text box style let's go ahead and save if i'm using the correct one text field style and rounded for attack this one there we go and we want it to be a little bit on the top so i'm going to go ahead and say spacer but you can see right there on the top that's fine i can also go ahead and put this into a horizontal stack and add a button just to the side instead of the bottom there we go great looking fine now it's pretty simple and after that i can go ahead and add a list now right now i'm creating a list so i'm just going to go ahead and hard code some stuff so i'm going to just say that this list is eventually this list is going to display the list of item but we don't really have any list of items so i like to start with simply adding something over here all right so that something is simply the index so let's go ahead and display it there we go obviously these are not our task items eventually we will be able to display the hash item but right now it is fine so now the question is once we click on the save button what should happen we should call task listviewmodel.save which is our function in the task list viewmodel right over here the tasklistviewmodel doesn't really do anything we should probably get access to the title which we already have but looking at over here we don't even have any entities to begin with so let's go ahead and add an entity i will call this entity a task because that's what we're adding and this will only have one attribute title is fine it will be string and it will be required because that's the only thing we're adding so we're just going to make sure that it is required let's go ahead and build it great now going back to our task list view model the title should already be populated because we have binded it right over here so that should already be there using the title we can construct a task object so let's say task equals to task and you can see that right now it's not even coming off as a task object you can see that's not even recognized sometime you do have to well sometimes you have to import i guess core data but sometimes you also have to you can see it's not coming up so what i have to do is probably go ahead and restart my app xcode again and maybe it will pick it up all right so now i have restarted my xcode after quitting and now i should be able to see the task okay so let's construct a task you can see that this task object is coming from the core data entities and in order to create this i need a manage object context which i should be able to get from core data dot shared well in this case code not code data sorry code data manager dot shared dot persistent container dot view context now we have to like write a long line of code uh possibly we can actually go ahead and minimize this so let's go to the core data manager and call this view context which is ns manage object context and this is simply going to return us the persistentcontainer.viewcontact so we don't have to write that long now a little bit we can just remove this part so this is going to give us the task object and that task object we can set the title to the title that the person has actually typed in and after this we can use the core data manager to save it so i can go ahead and call core data manager dot shared dot saved task which by the way doesn't exist or we can simply just call save because it's going to be common for every single entity anyways so let's go back to our code data manager save and all the save is doing is that getting access to the view context and calling save on it this function can actually throw an exception so we will have to make sure that we are putting it inside a do catch and if there is any exception we're going to catch it and we can say view context dot roll back so roll back the changes don't do anything and after that it is completely kind of to you i mean if you want to go ahead and print out the error we can go ahead and print out the error by saying error dot localize description and you can print it out but if everything is fine then you should be able to save the actual task let's go back over here so after saving the task which is right here we can do something else perhaps you want to fetch all the tasks we can do that also so we have to write a separate function which will be responsible for fetching the task let's go ahead and call code data manager dot share dot save so that we know that it is saving going to the content view let's go and refresh it you can see right there we are calling the save function and the next thing that we want to do is to retrieve all the different tasks so let's go back to our task view model and over here we're going to say function get all has and we can say core data manager dot shared dot get all tasks which you and i both know this does not really exist so we have to go and implement a function called get all tasks let's go to code to manager function get all tasks which is going to hopefully somehow going to return an array of tasks now in the task object or the entity there is a function called fetch request which is going to return your request and that is something that can be used to perform the fetch request so if i go ahead and let's see what's going on over here let's go ahead and say over here tell it that it is a fetch request which is of type task just going giving it a little bit more idea and now we should be able to use view context dot perform perform i guess fetch there we go not perform but fetch passing in the request and couple of different things the view context can actually throw an exception so make sure that you are calling it inside do and catch block there we go and we can also return it in the catch we can simply go ahead and print out the exception whatever the exception actually took place uh well the catch actually must return something so in this case i guess we can return an empty array so we didn't really find anything i think we are returning now in this case there we go now let's go back to the task view model we are getting all the tabs these are the task model object and in order to display something on the screen it's usually a good idea to use the power of view models so i'm going to go ahead and create a task view model which is going to take in a task and it will expose some properties so that it can be displayed on the screen so right now i'm going to go ahead and take the property probably go ahead and say title and we're going to go ahead and display task.title and or it will be empty string i think another property we can possibly do is u is a id property and i believe it is the object id or core data manage object id let's see if we have the manage id over here let's see over here do we have a manage object id this one and that will be task dot object id believe yeah so we can return that also now get all tasks is going to return you an array of tasks but we want to construct an array of task view model and once we publish or once we have array of task view model we can put it in task array which is an array of task view model which i can initialize to be empty string and mark this with published and the way that you will convert it is you will map over it and you will simply say it has to be modeled in it which means that for every single item which is a task you are going to construct a task of your model or pass it to task view model and then we will go ahead and assign it to task perfect and now it's time to actually display it so let's go over here and try to construct this part so this will be task list view model dot task which is an array of task view model and i don't know if you can say self over here may i i may have to say id because i think that's what we're exposing and then the task over here which will be every single item in the task array and i don't think i need that stuff i can simply say test.title perfect go ahead and run this and see if that allows us to add a task or not it's running for the first time and i'm not sure if we need that but here we go so task let's say wash the car first thing you will see is that we did not display anything over here because i believe that after adding what you want to do over here after saving it is testviewmodel.getalltask so let's go to do that okay but still it doesn't display right now okay that's fine let's go ahead and say mo the lawn and there we go feed the rabbit there we go now the reason that it doesn't display these tasks when you actually load it is because we don't have an on appear over here so let's put an add-on up here and call task list view model dot get all tasked there we go perfect now the next task for us is to delete a task all right so now let's go ahead and move to delete functionality if i go ahead and run the app you can see it is displaying us watch the car mow the lawn feed the rabbit all the task list so we are able to do the read part and we can go ahead and do the add part if i say do the grocery there we go perfect now so how do i delete i want to delete when i swipe the row from right to left and i should see the delete button in order to do that i can go ahead and use a for each loop to do this thing all right so let's go ahead and see that how we can use it for each loop if i'm having a list i can go ahead and save for each and i can pass in some sort of a list as which in this case is task and the id so that part kind of remains the the same the displaying part of it will get access to the task and we can go ahead and display a task so task dot title if i run this i should get a similar result but with for each we can also get access to the delete by saying on delete and we can perform an action so on delete and we're going to perform an action over here so i'm just going to say delete perform and then i will simply say delete task the delete task over here will be a function that i will implement i can implement it over here also but just to keep it a little bit clearer i'm going to go ahead and implement it over here delete task add offsets which is index set so that's the signature you need in order to comply with the on delete now when we are performing the delete which is we are doing it over here we need to go ahead and go through the offsets dot we can go use the for each i believe we will get some sort of an offset using the offset which basically is just a number in the end offset dot let's say if it has a value or something we should be able to get let's just call it index i guess okay so we are going through this all of this stuff and we should be able to grab the item so let's say task equals to task which is an array which is task list dot task and then passing in the index so this is going to give us the tasks that you actually do want to delete you can pass the whole task to the core data manager to delete the task or i can simply say task vm something dot delete the task i'm passing in the task that i want to delete we don't really have any delete function in our task list view model i'm going to go over here and check out that if we can create a function we will call it delete and you're going to pass in a task that you want to delete okay let's see why the build is failing uh we are passing in the oh we have a not a okay last thing let me actually do this there we go this is tax review model not it has the ui does not have access to the task entity it only knows about the view models this viewmodel does have a property called id which can be used to delete a particular task one of the issues that you will find over here is that we have the task but we don't know what object we have we need to use the task id to get the task object and then perhaps we can call it delete on it but right now we only have the task view model and we don't have the actual object like the entity that we want to delete so i'm going to go to the code data manager and i'm going to go ahead and say over here get task by id where you can pass in the id which will be of type manage object id and eventually it will somehow return you the task object this is also going to confirm that you have a task object that you're trying to delete all right now there might be different ways we can do view context dot and i believe there is something called object with id or let's see over here existing object with id there we go we can pass in the id and looking at the signature of view context.existing object which is this one you can see that it is going to return you a ns manage object all right so if i go ahead and simply go ahead and say okay go ahead and return whatever you're returning over here it's not going to work like that if i go ahead and convert it to a task like this it's not going to work like that either all right so we need to find a way to make sure that we are able to do this thing the other thing is you need to have a try catch block over here so i'm going to say try and if i'm using try i need to wrap this in like this catch well in catch what can we return we can perhaps change this and return nil over here or you can even throw an exception saying that well we don't really know i mean what are we supposed to return in this case all right so let's see that how we can perform existing object and that returns as the manage object so how can we convert it into a task to return this so let's go ahead and do that there we go and we can convert it to task perfect this means that the get task by id function can be used if you're looking for a task using their id let's go back to our task list view model so when we are deleting the task which is right there the first thing is to actually make sure that the task exists so i'm going to go ahead and say existing task equals to and i can pass in the task id into the core data manager so code data manager dot shared dot get task by id the function that we just implemented and i can go ahead and pass in the id this is going to give me the existing task and on the existing task you can see that it's different things available over here like it's deleted and all that stuff right so now the question is okay if we even got the existing task how do we delete it once we have the existing task we can go to our code data manager and create a function called delete task which is going to take in a task object and it's just going to delete it all right so we can go ahead and say view context dot delete and the object task but just by deleting it it's not really going to work you do have to make sure that your view context is actually saved and we already have the save function which we can fire just to make sure that it is actually saving so let's go ahead and call the save function over here there we go so this means that go ahead and save the contents of the view context which will actually save your view context and everything in it which means that it will delete the task let's go over here and now we can go ahead and call core data manager dot shared dot delete task passing in the task sorry existing task there we go and i guess this is going to return us so let's go ahead and say existing test let's go and unwrap it i'm just going to use if let existing task equals to existing tasks and now we can hopefully call existing tabs right there because it is unwrapped now let's go back to our content view and make sure that we are calling this function there we go once again after you call the function it will be a good idea to refresh the list so i can go ahead and say get all tasks which are going to refresh the list hopefully and show us the updated list with that particular task being removed so we have couple of tabs let's say that i'm done with mowing the lawn i can go ahead and swipe it and i can delete it let's go ahead and run the application again just to make sure that that particular task is gone and you can see it's gone more the lawn is gone feed the rabbit do the grocery gone let's go ahead and add some tasks let's say file for tax i think the tax date is now extended but there we go do or go to gym there we go so we can add all of these stats one delete the task and all that stuff so now you have learned that how you can use the mvvm design pattern when you are working with a sif ui app for core data and i hope you have enjoyed this so that's pretty much it hope you have really enjoyed it now if you want to learn more about core data then check out my brand new course core data in ios it covers mvpm surf ui as well as cloud kit it was just please a couple of days ago and you can see i have close to 230 students and it is already a best seller right there you can see and it covers a lot of stuff it's a 8.5 hour course and you can see it goes through a lot of different things related to core data even refactoring the application creating base classes relationships and or and also cloud kit so definitely check out this course the link to this course will be right there in the description of youtube i've also added another thing which is for my bigger fans i guess buy me a coffee so you can see the url right there if you are interested in buying me a coffee to show your support then this link will also be there right there in the description and you can just donate any amount uh for me to buy a cup of coffee i actually like to drink coffee and uh that will be great i mean that will definitely show your encouragement show your uh you know appreciation so check out that link ko hyphen f i dot com slash adam sharp for buy me a hot cup of great coffee thank you so much and hope you have enjoyed this video
Info
Channel: azamsharp
Views: 5,858
Rating: undefined out of 5
Keywords: swiftui, ios development, swiftui tutorial, core data swiftui, swiftui mvvm, swiftui core data mvvm
Id: ehV2gp5uVhs
Channel Id: undefined
Length: 32min 10sec (1930 seconds)
Published: Mon Apr 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.