So, now that we've managed to make our to-do list app work using Realm to create new items, to save new 1
items, to read the data from our Realm database, it's time to tackle updating data in the database. And you'll 2
find that similar to Core Data, updating data is very, very similar to saving a new item, 3
and we're going to be using realm.write to do the same thing. 4
So the place that makes the most sense to update are realm is, again, inside our didSelectRowAt 5
indexPath Method. 6
And this is the place where we select a cell inside our tableView in order to check or uncheck it by 7
toggling this particular done property. 8
So we're going to leave all of this commented out and I'm going to show you how you would do this using 9
Realm. 10
So what we can say is we can say if let item = todoItems, which, remember, is a container that 11
contains a whole bunch of items and it's fetched from our realm, then we're going to grab the item at 12
indexPath.row, 13
so, the current selected row. 14
And if this is not nil, then we're going to be able to access this Item object, and we can say 15
try realm.write, 16
and we're going to write item. equals the opposite of item.done. 17
And because this can throw, then, again, we're going to wrap it inside a do catch block. 18
And if there is an error, then we're going to say "Error saving done status." 19
Let's just indent this for clarity sake. 20
And now we have replaced this code. 21
So just to run through it, we're checking to see if to-do list items is not nil, 22
and if it's not, then we're going to pick out the item at indexPath.row and set it to equal item, 23
and then we're going to try and write the updated property of item by toggling whatever it used to be before. 24
So if it was false, it becomes true, true becomes false. 25
And the last thing we need to do is, of course, call our trusty tableView.reloadData method to 26
call this cellForRowAt indexPath method again and to update our cells based on this done property. 27
And give it a check mark 28
if it's done and remove the checkmark if it is not done. 29
So all that's left for us to do is to run our app and see if it works. 30
All right. 31
So let's head into our Shopping category where we know we've got some items and let's select and say 32
that we're done with buying peaches. And you can see that we've got a checkmark showing up and we can 33
toggle these as we please. 34
And if we have a look inside the Realm Browser, you'll see that as I check these, they get updated in 35
real time and really, really fast as well. 36
But when I check them over here, they will not get reflected in our table view because, as you remember, 37
we cannot call reload table view from a different application into our app, 38
so it has to happen over here. 39
So that is how we can update our data using Realm. In the next lesson, 40
we're going to talk about how to delete data using Realm. 41
So all of that and more, see you on the next lesson.