This workshop will be retired on May 31, 2020.
Bummer! This is just a preview. You need to be signed in with a Pro account to view the entire video.
Inserting Data19:25 with Amit Bijlani
Learn to integrate the Realm framework into your project and insert data into the realm database.
All right, so I have created a shell of an application, 0:01 which are starter files basically. 0:04 it contains a table view controller. 0:06 Where all the items are going to go off our shopping list. 0:08 And when you click on Add, it goes over to the Detail View Controller. 0:12 Which contains the item title the quantity and a category. 0:16 However, we're not going to worry about the category for now. 0:21 We're just going to worry about the title of the item. 0:24 Like what are we buying in our shopping list. 0:26 It's a grocery shopping list. 0:29 So, we're buying fruits, vegetables, housewares, cleaning products. 0:31 Whatever in the quantity. 0:36 And when you click on done, it goes back over to the table view controller. 0:39 All right, so first things first. 0:43 We need to add the Swift framework to our projects and 0:45 for that we need to head on over to realm.io. 0:51 And once you get to realm.io, you're going to click on docs. 0:56 And then, you're going to select from the realm mobile database whether it's Java, 1:01 Objective C, React Native, Swift or Xamarin. 1:05 In our case it is Swift. 1:09 So we click on Swift. 1:11 Click on Getting Started and then, you're going to click on download. 1:14 Once it has downloaded, 1:20 within that folder you'll see several different of sub folders. 1:22 So there's iOS, OS 10, TV OS, Watch OS. 1:26 There is the plug in and you have examples. 1:30 So if you click on iOS, it will give you the various versions of Swift. 1:35 We're working with Swift 3.0, so that's what I have selected here. 1:39 And then, we'll head on over back to X code. 1:45 Click on the project's. 1:50 Click on general. 1:52 You're going to scroll all the way down and 1:54 under embedded binary, that's where we're going to drag and drop these two files. 1:58 I will just drag and drop here. 2:04 Make sure that you select copy items if needed and then, hit finish. 2:10 So just to tidy things up, I am going to drag it under this grouping called 2:18 frameworks that I've created, all right. 2:23 So the next thing that we need to do is, create model objects. 2:27 So in our shopping list application, the model object that we need 2:32 is a shopping item that you're going to add to your list. 2:36 So, we'll create a swift file and we'll call this item. 2:40 So since this is a realm model object, 2:45 we first need to import RealmSwift. 2:51 The next thing we need to do is, say it's a class item, which sub-classes object. 2:55 All Realm model objects need to subclass object. 3:03 So that the Realm framework knows that these are the model objects basically. 3:07 And that these are managed objects that they are managed by the ram database. 3:13 And it can store data and persist data into the ram database. 3:17 So the next thing you need to do is, define our properties. 3:23 So in our case, instead of just saying var, we have to say dynamic var. 3:27 And in this case, we'll say title and we'll initialize it to an empty string. 3:32 We'll say dynamic var qty = 0. 3:38 So, why did we use the keyword dynamic? 3:44 Well, we use the keyword dynamic, because it means the getters and 3:48 setters of this class are synthesized by its superclass. 3:52 In this case by object, 3:57 which means these properties are going to be managed by the superclass. 3:59 All right, so that's all it takes. 4:04 That's how we define a model object in Realm and now, 4:06 we need to use this model object. 4:10 So, I'm going to go over to our master view controller and 4:13 this is where we need to define our data source. 4:16 So, what is our data source? 4:19 Well, our data source is an array of items. 4:21 Now what we want is, something like a fetch results controller, right. 4:26 In a code data, you have a fetch results controller. 4:31 That mediates between the persistent store, which is your database. 4:35 And your Table View Controller, where it manages the object graph. 4:40 What data is going inside it. 4:45 What data is coming out of it and then, it notifies the UI that, hey, 4:47 something happened. 4:51 And so, that you can update your user interface or 4:52 automatically updates your table view controller. 4:55 In the case of REM, you have a results class, right. 4:59 So, you can query it and you can get back results and 5:05 you know you can chain queries with the results. 5:08 So we'll come back to results, but we need an array of items. 5:13 We have created an item model object and we need an array of them. 5:18 So here, I'll declare var items. 5:23 So, this is a simple array of items and I'm going to put a question mark, 5:32 because it's an optional. 5:36 We don't have an initializer. 5:37 And over here in number of rows, I'll just say, 5:41 items.count and if that is nil, then we'll say zero. 5:46 And then, we need the cell for row at IndexPath. 5:57 So, declare a cell. 6:02 We'll say cellis equal to table view.dqreusable cell 6:03 with identifier index path. 6:08 So, the identifier is declared in our main.story board. 6:13 If we go over here, we can click on the cell 6:17 And look at the properties inspector and 6:25 see that our identifier is cell with a capital C. 6:28 All right, so cell and the index path, well index path is being passed to us. 6:35 So, that's index path. 6:41 We'll say, let item equal items indexpath.row. 6:43 Then we'll say, cell.text.label.text = 6:50 item.title and finally, we return to cell. 6:55 And I believe the compiler is complaining, 7:03 because it says it's immutable and we need to declare a mutable cell. 7:06 So we'll say var, because we are modifying it and that's an optional. 7:12 So, we can wrap this in a if let statement. 7:21 All right, so now it's saying we can change it back to a let. 7:34 All right, so this will display a list of items. 7:37 That's great, but we need to have a mechanism 7:42 off inserting items into the realm database. 7:47 And this is where the Detail View Controller comes into play. 7:51 So we'll go into the Detail View Controller.And when the done 7:56 button is tapped, we're going to see how to add data into our ram database. 8:01 So what we need to do is get the title that the entered in the text field. 8:12 And we need to get the quantity that they entered in the quantity text field. 8:17 So we'll add a couple of guard let statements. 8:21 So we'll say guard let title=title 8:24 text field.text,let 8:31 quantity=quantity text field.text Alt. 8:36 We're going to put this out in a separate function. 8:44 We'll say dismiss. 8:47 So instead of calling this in two different places, 8:57 we have factored it out into a separate method. 9:00 So just say dismiss true, 9:05 in here as well, dismiss true. 9:09 I'll delete that from this method, right. 9:16 So now we have two constants, our title and our quantity. 9:21 Var item is equal to item. 9:26 So in this case, we're just assuming that we're creating a new item. 9:32 We'll later on see how we can update an item. 9:36 So item.title is equal to the title 9:39 and item.quantity is equal to quantity. 9:45 So now that we've created a new item, we need to store this item into rum database. 9:51 So in order for us to store this item into the rum database, 9:57 we need a reference to rum. 10:01 Like a mechanism to communicate with rum. 10:04 And you can do that with one line of code. 10:08 With core data you have to have a managed objects within the manage object contacts. 10:10 Which has a persistent controller, all of those crazy layers. 10:15 In this case, no crazy layers. 10:20 Just one object, which is realm. 10:23 So we'll let Realm equal to try Realm. 10:28 That's it. 10:33 And then we'll say realm.write and we'll say realm.add. 10:37 Because we're adding a new object to the ream database. 10:43 Right, so we have a few compiler errors. 10:47 Let's see what the first one is. 10:50 It says use of unresolved identifier realm. 10:51 That's because we have an imported realm swifts because we're using realm 10:55 under swift. 11:00 So we have to import realm swift and so that compiler warning has been silenced. 11:01 Now let's see what is this one. 11:09 It says cannot assign value of type String to type int. 11:11 Right. 11:17 So when we declared this round model object, it is an integer. 11:18 What we get back from the text field is an string, because text is of type String. 11:25 So what we can do is, inside this guard let, we can now type cast this. 11:32 We can convert this from a string to an integer and it is complaining. 11:38 It's saying optional. 11:44 All right, so we're going to implicitly unwrap that. 11:46 Finally, once again, it's complaining. 11:50 It's is when we do a write transaction, it throws an error. 11:53 And we're not catching that error. 11:59 So instead off actually just forcing a try over here, I would rather do a do block. 12:02 Now let's do a try. 12:12 So in a real world application, we will catch this. 12:16 And we will gracefully display the error message to the user. 12:21 For now, I'm simply going to print it out to the console. 12:27 But we should gracefully display an error message to the user saying like, hey. 12:30 We were unable to save this item to the database. 12:35 All right. 12:38 We still have some things. 12:40 It's a item was never mutated. 12:42 Change this to constant and filing this one. 12:46 It's a guard body me not fall through. 12:51 So the problem is that we call dismiss. 12:56 We will also need to call a return. 12:59 We're putting it all on the same line. 13:01 We're going to put a semi colon. 13:04 And say return and this will dismiss the view controller. 13:06 And to get out off this method the done 13:12 All right, so let's recap what we did here. 13:18 We got an instance of Realm. 13:21 We created a new model object and saved, assigned values to the properties. 13:24 And then we simply created a write transaction, 13:31 where we instructed round to add a new object to the realm database. 13:34 And since this right transaction can throw an error, 13:40 we wrap that in a do catch block. 13:43 Right, so let's run our application once again and see if that works. 13:46 So, I am going to add apples to my shopping list, because I love apples. 13:54 Now, let's say six apples and we hit done. 14:00 And nothing shows up in our Table View Controller. 14:05 So hit stop. 14:09 And I will hit run again to see if actually save something to the database. 14:13 So nothing happened here. 14:20 Then actually write ending thing to our database. 14:22 It's either that or I messed up in the Table View Controller. 14:27 Let's see. 14:32 Right, so I have an array of items. 14:33 But I am never instructing the round database to 14:38 extract that array of items from the database. 14:41 See, we're just declaring an array of items. 14:45 But nowhere am I saying I'm split, 14:48 nor am I saying like hey real, give me this array of items from your database. 14:49 So let's do that. 14:54 So, do import realm swifts. 14:57 Some going to get an instance off realm over here. 15:02 We'll say realm is equal to try realm. 15:05 And this will be a property for our view controller. 15:10 And we'll create a getter method. 15:15 And inside this getter method, we will use the realm property, 15:19 we'll say realm.objects. 15:22 So in our case, we want all the items to be displayed in our view controller. 15:26 So you can use this convenient method that says objects of type whatever. 15:32 And if you have a primary key, then you can specify the primary key. 15:40 So in our case, all we have is the object of Type item. 15:45 So I'll say objects, type item.self or of saying like all right off this type. 15:50 To give me back all of the object of this type. 15:58 Now this method, if I command click on it, it returns a realm swift result. 16:02 That's what it's returning. 16:10 It's returning a type Results. 16:12 So let's Cmd+click on Results and see what that is. 16:15 So results is a class. 16:19 And if I scroll up here, it says, 16:22 Results is an auto-updating container type in Realm returned from object queries. 16:25 Results can be queried with the same predicates as list. 16:31 And you can chain queries to further filter queries. 16:35 So it can give us back results and we can display these results. 16:41 You can index into them. 16:46 You can subscript them, you can get first last. 16:48 So results kind of behaves like an array. 16:52 And if you wanted an array, you can see value for a key. 16:57 Where you're actually specifying the key if you're returning back a dictionary. 17:00 So has all kinds of methods if you're going to round up IO. 17:07 You can get further help. 17:12 You can see a collection and you can look at results and look at the API. 17:15 You can read through what kind of methods results provides. 17:19 All right so instead of this being an array of items, 17:25 this is really going to be of type results. 17:28 And since this is a generic type, 17:32 we're going to specify that it's a results of item. 17:33 What happens to the rest of our ViewController. 17:38 Now this is no longer an optional, so 17:40 of course we're going to get some errors in our code. 17:43 So the compiler is saying delete the question mark because it's 17:47 no longer an optional. 17:50 So if we delete that, then we need to delete the nil coalescing operator. 17:52 And here, we're going to delete this as well. 17:56 All right, so now we can run our app. 17:59 But it won't let us run it because we have an if let statement here, all right? 18:04 We can get rid of that as well. 18:12 Okay we are running our application. 18:18 So hopefully, it displays that one item that we added. 18:21 Great. 18:25 Now if I add another item. 18:27 Let's say I added bananas and I want 12 bananas. 18:29 Hit done, and wow, there is our item bananas. 18:37 And let's say I'm going to add Windex, that's a window cleaner. 18:43 At least here in the United States. 18:51 I need one of those, then I hit Done and there you go. 18:53 There is our Windex. 18:56 So as you can see, in a few short minutes, we were able to create a model object. 18:58 Access the round database. 19:03 And persist data to the ROM database. 19:05 All the while displaying that list of items in the Table View Controller. 19:08 So coming up in the next video, will see how we can update each item. 19:13 And we can delete those items and finally we will see how we can 19:17 categorize the items using the category relationships. 19:21
You need to sign up for Treehouse in order to download course files.Sign up