Core Data in Swift
Transcript
(dramatic music) - [Animaker Voice] Stanford university. - [Lecturer] All right, here we are, lecture 12, Stanford CS193p Spring of 2020. Today's topic is Core Data, which is an object-oriented database. And we've been doing a lot of functional programming this quarter. Pretty much all the stuff we've been doing has been functional programming. We're gonna switch over now to doing a little bit of object-oriented programming. Probably won't even notice the difference here. Although Core Data is based on object-oriented programming and Swift supports both object-oriented and functional programming equally.
And we're essentially gonna use this Core Data infrastructure to store and retrieve objects or classes in a database. Now, there's a very mature technology out there, it's been around for a long time to store large data sets, it's called SQL. But programming in SQL is very different than the kind of programming we're doing in Swift, SQL is a language and it has its own syntax and it's quite quite different. And it would be a bummer for us if all of this learning we've done about how to program in Swift, couldn't be applied to storing data. So we're gonna get the best of both worlds here
because Core Data actually does its storage in SQL, but we are going to interact with our data entirely in an object-oriented way. We're not even gonna need to know a single SQL statement to make this happen. Now, the heart of making this work in Core Data is this map. And it is a map between the objects and the vars on those objects, and the tables and rows of a relational database. Now, if you don't know what relational databases are and all that, you really don't need to know
because you're gonna be focusing on the objects and vars, not on the tables and rows in a relational database, and Xcode has a built in editor for this map, which is really great. And this editor doesn't just let us specify the objects in vars, it lets us graphically create the relationships between objects, because that's really the important part, not just to have objects with vars on them, but you have objects that have relationships to other objects. And we'll see that some examples of that, in a minute and in big time, we'll see that in the demo.
So then what, you create this map, what can you do then? Well, Xcode behind the scenes is gonna generate the classes, right, the code for the classes, that represent those objects and vars you created in the map. And we get to use extensions just like we do with any other kind of data structure. We get to use extensions to add our own methods and our own computed vars to those classes, because, the storage vars are stored in the database. Then these objects that have been created for us and that we've extended, service the source of data for the elements in our UI. So all of our SwiftUI, that's doing everything, it's obviously putting data on screen, right now we store them in ViewModels where we have Arrays and dictionaries and all that stuff. Well, now this data is going to be coming from this database and we're just gonna be accessing these objects to put it on screen. Perfectly naturally, like we would normally do.
So what are the features of Core Data? Of course, it has features for creating objects. You have to be able to create objects in the database, and it very naturally lets you change the values of the vars on these objects, so you just change them. They're just vars and you set them equal to something, boom, you just change data in the database. And it even has beautiful infrastructure for establishing these relationships between objects. It's just a matter of setting a var basically to create a relationship between one object and other and by relationship I mean things like a flight has an origin airport. So flight objects and airport objects, they have a relationship. And there's of course a way to save these objects and really important that you can fetch the objects from the database based on certain criteria. You wanna say, I want all the flights that match this certain criteria, arrived at this certain time or whatever that might be. It has a great simple API for doing
the fetching of the objects. Now it has a whole lot of other database features on top of it, optimistic locking and all this things. We are not going to talk about this. This is an intro course, so we're just introducing the concept of Core Data here, but there is a lot of stuff in there to take this to pretty high levels. Now let's talk about the integration of SwiftUI, with this Core Data database. The objects that we create in the database are ObservableObjects. They're essentially little mini ViewModels, and there is also a very powerful property wrapper in SwiftUI called @FetchRequest,
which fetches these objects for us. So this FetchRequest is more than just a one-time fetch. It's kind of a standing query, that's just constantly trying to match whatever the criteria you're talking about are, and returning whatever's in the database. So as things get added to the database, if they match the criteria of that FetchRequest, then it's going to update your UI. That way our UI is always in sync with the database really, really fantastic.
So how do you get Core Data into app into your app? How do you set it up? Well, the real way to set this up is when you create a new project, there's that button that you saw called Core Data, use Core Data. And you're gonna click that, and it's going to do a little bit to set you up. Now, if you've already got an app and you've decided, oh, I wanna add Core Data to it, I recommend going back and creating a new project and clicking this button and then moving all your source code over because this button does such a really nice job of setting things up. So what does this button do? Well, it creates a blank map for you. This map that I told you has a built in editor, you got a blank, one of those, so you can start adding your objects and your vars. It adds a little bit of code to your AppDelegate, which I'll show you in the demo. You haven't seen it yet. It's really nothing, much of interest in there to us, but it does add this little bit of code
that creates the database store, the actual SQL database, that the stuff is gonna be stored in. And so you don't ever need to go look at that code, even, it just all happens automatically. I just wanted to let you know that it does do something in there. Now it does add a couple of lines of code to your SceneDelegate, right where you create the content View there. One of the lines of code goes and reaches into that store, the SQL store code that was in AppDelegate and it grabs something called an NSManagedObjectContext. And this context is crucial to using Core Data. It is the window through which we see that all the objects in our database, and you're gonna see that we need to contact whenever we create objects, we do fetches, any of that stuff. So this two lines have SceneDelegate code order, go grab that context out of the store. And then the second one, interestingly is to pass that context into your SwiftUI Views via the Environment.
And we already saw Environment, for example, with the edit mode. And this is using Environment again, so that all your SwiftUI Views will have this context so they can see the database and get objects out of it and all that. So that's added to your SceneDelegate. And that's pretty much all the set up you need, because now you can create objects, fetch them, whatever you have the window into the database you need, you've created your map, whatever the objects in vars you want, and you're on your way. So let's take a look at that map. I'm gonna, since the demo is gonna create detailed map with airports and airlines and flights in our on route, there's no reason to go over it here, but just to give you an image in your mind, what it looks like, you know, here's an example on the left, we have a, looks like that is a Flight and it's got some attributes like when it arrived and or it's going to arrive, and it's ident, and even some relationships to other objects like, the destination airport,
the origin airport airline. And then on the right, you can see this graphical map of the relationships between Airports, Flights, and Airlines. For example, if you see Flight, it's got this relationship to Airport, which is the origin and another relationship, the destination, and notice that the Airport has relationships back along the same line, which is the Flights from this Airport, and the Flights to this Airport. Now, those origin and destination relationships in Flight, those are just Airport objects. That's the type of those vars, all those little black words you see there, code name, short name, aircraft, those are all just gonna be vars inside my Flight object, my Airline object, my Airport object, Airport object, and destination, origin are just vars and their type is gonna be Airport. Now the flightsFrom and the flightsTo, they're a little interesting because there's multiple Flights to and from an Airport. So those are actually gonna be Sets of Flights.
That's the type of that var, it's a Set, kind of an old Objective-C-style Set. And we'll talk about that in the demo, but that's what's going on there. So all of these things that we see on the screen are just turning into objects, Airline, Flight, and Airport objects, with vars, aircraft, arrival, departure file, those are all just vars on each of these things. That's what this map is doing. And that's really all there is to it with the map. So once you have this map and now you have the window that was passed into your Environment that we talked about from your SceneDelegate, what can you do? Well, you can get that window, that managedObjectContext via your Environment, it's \.managedObjectContext. And now you have this context var, and you can use it to do things like create an object. You just do that by saying Flight, with the argument context so that knows the window into the database and it'll create you a Flight.
Now you have a Flight this green flight var here, and you can just start setting the vars on it. Like the aircraft, set it to "B737", Boeing 737 aircraft. And here's another thing I'm creating an Airport called KSJC, and I'm just setting it's ICAO, which is its unique identifier for an airport to "KSJC". And I can even do pretty powerful var setting like if I set the Flight's .origin to ksjc, 'cause kscj is an Airport, and the origin is a var
that's of type Airport, then that sets that relationship. And that will also affect the opposite relationship of ksjc's flightsFrom, will automatically get flight added to it. So you don't even have to worry about the balancing, the two sides, one's a Set of Flights and one is the origin. It automatically keeps both sides. And if I had added it to the Set of Flights, then it would set it as the origin on the other side. So it's pretty cool system in that way. So it's just objects and vars. So you just that's looks all like objects and vars to us here. We don't know anything else about SQL or tables and rows, just objects and vars.
Saving it, really easy, context.save(), this throws, however, now why would trying to save it throw? Well, your disc before could be full, for one thing, it's extremely unlikely, but your iOS device doesn't have unlimited storage, but there could be possibly other errors, but you know, generally this is not going to fail, but it can throw. So that's why we have to put the try on there when we save. Now, what about fetching objects? Getting them out of the database? Well, we do that with this very important objects in Core Data called an NSFetchRequest. All right. And it has a don't care there, which is the kind of thing that you want to fetch. And you create one just by specifying the name of the thing in your map, that is that thing you're trying to fetch. So Flight in this case is what I called in my map, the objects that are Flight. So this is gonna create a FetchRequest that goes
and fetches Flights. That's what this request is. Now how does it know which Flight to go and get? Well, this request has a var in it called predicate, and you assign it an NSPredicate. You're definitely gonna wanna look in the documentation of NSPredicate and see all the incredible wide range of things it can do to specify which Flights you want. So for example, I've created a predicate here, predicate kinda has a little bit of a printf kind of feel to it. This has been around a very long time,
well before Swift ever existed. So it's a little printf-y. And so my predicate here is that I want arrival is before something, and the origin equals something. And then I provide the somethings. The first something is the current date and time. And the second one is ksjc. So this predicate means, show me all the things that have arrived before now. So they're already arrived, and their origin was San Jose. They came from San Jose. So that's the predicate I'm doing here.
So it's a little bit, you know, texty kind of oriented predicates there, but you have to definitely have to go look in the documentation for NSPredicate to understand all the things that it can do. So that's specifying which of the flights I want in a database. Now there's one other piece of requests that you need here, which is something called the sortDescriptors. And that's because when we make this request into the database, it's gonna come back as an Array. And that Array has to be sorted. And we specify the sortDescriptors so the sorting can happen on the database side, SQL database is super good at sorting things. And so we're gonna let it do the sorting if possible. And we do that with this sortDescriptors var, it's just an Array of these NSSortDescriptors, and a SortDescriptor simply say, what var, ident in this case, that's the Flight identifier, that you wanna sort by, and whether you want it ascending or descending, right, alphabetical order A to Z or Z to A.
How do we then ask our context, our database, go fetch these things for us? We do that with the fetch function. So we say context.fetch this request and it going to go out to the database and go find all the flights and match this arrival and origin predicate that we have, and return them to us. Now, this fetch also can throw, just like save can throw, so can fetch, and so we'd need to try it. And a lot of times we'll do a line of code like this, let flights = try? and then the context.fetch.
If we do this, then that flights var is either gonna be nil, if the fetch failed, empty Array, if it did not fail, but no flights matched our predicate. Otherwise it's just an Array of flight objects, the ones that matched. So again, very object-oriented. I'm just getting these Flight objects that match my predicate. I just threw all of this on one slide, just so you get a feel for all of the code. And so you have kind of a quick reference guide to it, but we are of course, going to do a big demo, shows all this stuff happening. Now what about the integration with all this stuff and SwiftUI? Well, there's two major points of integration we talked about. One is this ObservedObject. When you have a flight, as a var in one of your SwiftUI Views, it's going to be an @ObservedObject. You can then use it to do like Text(flight.ident) here, and just show the ident and apply whatever you wanna do, it's just an object.
The ObservedObjects, by the way, as far as I can tell, do not seem to fire automatically when things change in the database. So if you want them to change, you need to explicitly call objectWillChange. But these do make these Flights and Airports and Airlines feel like little mini ViewModels. And that's really what they are. They're little ViewModels, on a little flight, but a lot of times what we wanna show in our UI is more than just one Flight or one Airline. We wanna show all the Flights, for example, that match a certain FetchRequest or Predicate. And so there's another really important feature in SwiftUI, called the FetchRequest property wrapper. Now this property wrapper, you create it with the arguments, either the same arguments that go to a FetchRequest, which is the entity, remember that entity name thing was Flight,
and the sortDescriptors and the Predicate. So you can create a FetchRequest that way, or you can actually create a FetchRequest just by giving it a FetchRequest you created, either way you're specifying what things you want to fetch. And this is a property wrapper, right? So it's wrapping some var. And the type of the var that wraps, is called a FetchedResults, also has a don't care, and that don't care of course is what kind of thing it's supposed to fetch. So that better match whatever your FetchRequest says that it's trying to fetch. Now this FetchedResults var, it's a Collection. So you can pass it to ForEach as you'll see in a second. But so it's not an Array, but if you wanted to turn this thing into an Array really easy, you could pass it to an Array as Array's initializer 'cause an Array knows how to take any Collection and turn it into an Array. You could also send it messages like sorted, sorted can be sent to any Collection,
and it returns an Array. And that Collection is full of those kinds of objects which you're fetching, Flight objects or Airport objects. Now what's cool about this var that you're creating here, Flights or Airports is that it's continuously trying to fetch that FetchRequest. All right, this is not a one-time fetch, where it's gonna fetch out and give you the results. It's continuously doing this fetch. It's like a standing query. And so every time a new Airport or a new Flight is added
there, or even if an existing Airport or Flight changes one of its vars, so that now it matches your predicate, it's going to update. And when it updates, your SwiftUI is gonna get invalidated and redrawn. And so your UI is always going to be showing what's in the database. You don't ever have to tell it to go fetch. And this is all part of the declarative nature of SwiftUI. You don't say to do things, in SwiftUI you just declare the things are a certain way, and they always are that way.
And of course, with Core Data, we always want them to look like whatever is in the database. So we tend to use @FetchRequests, sometimes even when we're just fetching one object, right? We might be having the predicate, just be like ident, equal something for a Flight, that's ever only gonna match one Flight. But the great thing is if that Flight changes, this is going to be updated. That's why the fact that the ObservedObjects up there, we were talking about don't seem to kind of do their objectWillChange when something changes. That really is not a big problem, because we would just maybe have a FetchRequest that fetches that one thing. And that will change, because FetchRequest is always tracking what's happening in the database. It's really a fantastic property wrapper. This API that you're seeing right here is a really elegant, simple one thing to make it so that your UI is always matching up against Core Data. So that's really, really cool.
By the way I show the FetchRequest up there. I'm creating it. When I declare the vars with the FetchRequest I want, but of course you could just declare it and I'll show you this in the demo and then use your init and set the _flights, right, _flights is the actual struct, the FetchRequest struct to be something you create then. So if you're passing the predicate in, for example, that you wanna use, you can pass it into your init, and then your init can just initialize that FetchRequest thing, just like we've initialized, Bindings this way, State with its wrapped value, you can do the same thing here. And we'll see that in the demo. And speaking of which, lets dive right into the demo and show you what it looks like to do all this stuff.
Our goal in this demo is to convert our Enroute, to use our Core Data database and store all the information that comes down from FlightAware into a database, and then build our whole UI by just looking in the database. Right now, we actually fetch this stuff. And as it comes back in FlightAware, we're showing it in our UI directly, here we're gonna fetch it all from FlightAware, put in a database, and then have our UI, totally just looking at the database. And this is a common kind of paradigm for developing an application that fetches data, instead of having to try and to keep track with it and get it all the latest information all the time, you just throw it in the database. And so you're always looking at the database and makes your code a lot simpler on the UI side. That's exactly what we're gonna do. Now, if you wanna use Core Data in your app, the best way to do it, is when you say "New Project" over here, click this button, use Core Data.
If you click this button, use Core Data, you're gonna get the small amount of very important code that hooks you up to a database, this additional button, by the way you use CloudKit, that's pretty cool. That will make it so that everything you put in your database gets mirrored up to iCloud. And that way the user will see it in all their devices in Core Data. Pretty amazing. We're not gonna do that part of it. This demo is already long enough, so we'll just focus on the Core Data part, but it's really not that complicated. If you're interested in that, you can certainly look up how to do that. Now, if you've already started your app, like we have with Enroute and you wanna add, Core Data functionality to it, I actually recommend doing what I did, which went right back and created a new project anyway, and then just copied and pasted all my code, dragged my files back into the new project, because this little switch, it does a really good job, by just setting things up.
And so let's look at that setup. Let's see what it is this little switch did. And really added two important pieces of code. One is right here in this thing called AppDelegate, which we haven't even looked at AppDelegate yet, but we're gonna look at it right now, and here you can see it's added this thing called Core Data stack with this persistent container right here. That's the thing that holds your Core Data database. And so we are going to use this, to access the database.
In our SceneDelegate where we create our little FlightsEnrouteView, notice it's added a couple of lines of code here, this context, which looks in that persistent container, we were just talking about it, get something called a context. In this context is then passed via the Environment to all of our Views. Now we want to be very sure that when we put up a new Environment of Views, like when we use a sheet or a popover or something like that, that we pass this along to it.
Now remember an Environment when you give it to a View, all the Views that are in it's body, actually in it's body, get the same Environment. So you don't have to pass them there. But if you do a sheet or popover now, you're kind of going off to a new base body. And so you do need to pass, and you're gonna see that, 'cause of course, we do do a sheet in this app, we have that filter flights. So this context is our window onto the database. Where is the database herself or what is the database? And the database is something we designed using this little folder right down here, which is also provided by that use Core Data. Here it is. This is all of the objects that we're going to create in our database. Now, remember this is an object-oriented programming layer on top of, in this case, a SQL database. A normal relational database. And so it's doing all the mapping for us.
We don't have no idea that that's a SQL database and we don't wanna know, we're just gonna create our objects. And that's what this tool right here, this tool that's editing this .xcdatamodeld file is letting us do, define what objects we want in the database, what vars are on those objects. So let's dive right in and create our objects. This is Enroute. What objects do we have? Well, we have the flights. That's the main object, all these flights that we're showing, but we also have some kind of helper objects like the airline and airport objects. So let's create Flight, Airline and Airport objects here. This entities is the list of objects that we want. And we add them down here where it says, add entity. So boom, there it is. Let's call our first entity, Airport. Let's add another entity, call this one, Airline, and our third entity, which is a Flight.
So we've created the object right here, but they have no vars. This on the right, over here is showing the vars, especially this part of the top of your attributes, and none of our objects have any vars yet of course. Let's start with the simplest one, Airline. It only has three vars. It has a code, and this code is of type String. So this is how we add a var, we just press the plus, give it the vars a name, and then it's type. It also has a name. The name is also a String, and that's the full name of the airline like "United Airlines Incorporated", something like that. But it also has a short name in the FlightAware information that comes back and that's like, "United" just short, short and sweet, not quite a nickname, but shortened name of it. And that's it. That's all that comes back from FlightAware
for Airline that we're interested right here. What about Airport? So Airport had a very important thing called the ICAO, that is a String, that's like KSFO or KDFW, KSJC for San Jose, that's it's unique code. You notice they all start with K as airports in the United States start with K. So that is very important one for us to have obviously, but they will also get kind of cool things, like we get the latitude and longitude. Those are Doubles. Those come across from FlightAware as numbers, and so we're gonna store them here in our database as Doubles. Got some other stuff like the location of the Airport. So for San Jose, that's San Jose, California
is the location of it. And we also have the time zone that it's in. When we fly around up there in the skies, all the pilots, everything is going on in GMT, right, Greenwich meantime. So it's nice to know, the time zone of the actual airport we're going to so we can convert to local time. And then all the airports have a name. Like I think San Francisco International Airport is its full name of SFO. That's Airports. What about the Flight? Flights have something called in FlightAware an ident. This is like UA475 United airlines, flight 475. That its unique identifier. We definitely wanna be able to uniquely identify our flights. Our Flights also have aircraft. So this is like, a String "737" or something like that. Of course we have the arrival time and departure times. Those are Dates, go Date here, arrival and departure.
And it turns out that Flights also have another Date, which is their filed departure, because some flights are still on the ground, they haven't left yet either delay or they're not scheduled to leave yet, but they've filed, the pilot has filed for a certain time that they want you to depart. So that's it. These are our objects and their vars, but there's one more piece to our object-oriented puzzle here, which is the relationships between objects. For example, a Flight has an origin and destination Airport. It has a relationship there, that a Flight also has an Airline. So we can add these relationships in this section here, relationship, but we usually don't do it that way. Instead we go over here, down to this editor style in the corner, and we switch from this kind of table-oriented one we're at, to this graphical version. And this is giving us the same information as we just had,
depending on a little graphical version and these individual vars, if we click on them, we can see the types and all that by going over here and bring up this third pane inspector, which we really have not looked at, all quarter long because SwiftUI doesn't really use it that much, but really valuable here. It's the fourth tab over in this inspector, and showing this location is the var and here's this type notice it says, "Optional" right here. This does not mean optional like Swift Optionals.
This means it's optional in the database. So this unfortunate, this has the exact thing name, but it really has nothing to do with that. All of these vars and Swift, will be Optionals. And that's really a design decision there that's made because your database might be corrupted and you might think that all of these things have values, but they don't. They're the object was started to be created and it failed, and so now these vars aren't set. So that's why these are optional. And I'm gonna show you a little bit of a design strategy or whatever in my code, to kind of identify the ones that really should never be optional, and cover them a little bit with some syntactic sugar, or really I'm just gonna use a computed var to make them not be optional. You'll see how we do that. But by default, all of these are optional and it has nothing to do with this switch right here. So we can set other things, default value and things like that.
But mostly what we're doing here in this graphical arrangement is to create connections between these objects. For example, let's talk about our Flight. It wants its destination airport, and its origin airport. So how do we do that? Well, we do that with the control key. So I'm holding down control, you can see the plus appears. I'm gonna drag from my Flight, over to my Airport here and let go. And it creates a little relationship here, a little line. Now this is just gonna be a var on each side, on the Flight side, it's currently calling this var newRelationship. I'm just double clicking on it right there, but I actually want this to be my destination Airport. I'm calling this var destination. Now, what type is this var going to be in my code when Xcode creates all the code that makes this object stuff work, this is just gonna be a var that is a type Airport, because the Airport is an object, we're doing object-oriented programming here.
Each of these is a kind of new object that Xcode is gonna create the code for us. It's really kind of cool. Now what about on this side Airport? Well, this relationship here is really like the Flights to this Airport. And this is Flights, plural, because if I have 20 Flights all going to the same Airport, well then this is kind of gotta be multiple Flights or something. How does that work? Because this can't be a Flight. This has gotta be like a bunch of Flights. And indeed the way we do that is we can inspect this particular relationship and say that instead of a "To One" relationship, where there's one Flight per Airport here, it is a "To Many" relationship and you can see that the arrow became double arrow. Now this is no longer just one Flight. It is multiple Flights, which makes sense. An Airport has multiple Flights that are heading to it.
And what is gonna be the type of this var, this var flightsTo? Its type is gonna be a Set of Flights. Unfortunately, it's not a Swift Set of Flights. It's the old Objective-C Set of Flights. So you're gonna see us having to do another little bit of cleaning up, syntactic sugar, computed var to make this into be what we want, which we really want it to be a Swift Set of Flights, not an Objective-C set of Flights. And this is one of the few places where Objective-C leaks through in Core Data unfortunately, but easily fixed. Now I'm gonna do another control drag from Flight up here, for the origin Airport. So that new relationship down here is origin, origin
and up here, this is the relationship on this side is flightsFrom, and this flightsFrom, is also a "To Many" relationship. So both of these are "To Many" relationships. And Airline, same thing as Flight, of course, every Flight is operated by an Firline, so we'll have the relationship here, called airline on this side. And similar here, this is flights. These are all of the Flights being operated by this Airline. So that is a "To Many" relationship.
Now all of this work we're doing here to connect these up and create these little relationship vars, we can see it back in the normal editor style right here. So here's Airline. It has flights, Airport has flightsFrom and to, Flight has destination, origin, and airline. So that's it. That is how we build our object model here. All the code that's required to make these objects exist and have all these vars exist, is totally done for us by Xcode. And we just hit build here. It goes through and creates all the code that's necessary to make that work. The only code we're going to add is in extensions. So we're gonna add some code in extensions here. This is object-oriented programming, of course we want our objects to do more than just have
these vars, we want it to have some behavior as well. We'll be adding that behavior using extensions. Let's go back now. Now that we have our whole object model here, we have all the objects we wanna create, lets go use them in our UI. So here's our UI code that we've built from last time, it's still based on this FlightFetcher mechanism, and we're gonna completely replace the FlightFetcher. I'm gonna eventually comment FlightFetcher out completely. And instead we're gonna use an object-oriented approach to building our UI.
By the way, before we get started, take a look at the top of this file, you see import Core Data. You wanna make sure you're importing Core Data in any files that you're gonna be doing this Core Data stuff in, otherwise symbols like NSManagedObjectContext are not going to be defined. Now I'm gonna start with this very important struct right here, FlightSearch, which currently is looking up airports by their codes and airlines by their codes. And I'm gonna switch this to be object-oriented. My destination is not gonna be a String like "KPAO", it's going to be an Airport. And same thing here. My origin is going to be an Optional Airport, and my airline is going to be an Airline. So this is going to totally transform all of our code
to be object-oriented. By the way, sometimes when you build your object model, the rest of your code, won't get the message about it. Like we still have undeclared Airport again, as Xcode can be building that for us behind the scenes. I usually will just try and build here, sometimes that'll fix it. Yeah that didn't quite get it. Another one to do is go back to your Model over here and just do a build, sometimes that'll get it going see if that fixed it over here.
And it looked like it did. So lemme see what kind of errors we got. So we still have bunch of errors obviously we have our whole code is based on this thing being Strings. And these are no longer Strings. So let's just work our way through the problems that we introduced by changing this to be object-oriented, and fix them one by one. And along the way, we're gonna learn a lot about how to create these objects in the database, how to go look them up and find them in the database. That's all gonna be part and parcel of using Core Data to make this stuff object-oriented. So let's start with the very first one. It says here, cannot convert value type String to expected type argument Airport. Okay, we already see one case here where it's using a String for an airport instead of the Airport object. So let's click on this, takes us to our SceneDelegate,
and sure enough, right here, we're trying to create a FlightSearch with a String, which again, destination applied search used to be a String, we just changed it to Airport. So let's create a little local variable to be our Airport here. And I'm gonna say, let airport equal something. And this airport has to be some sort of Airport object. Now it is possible to create an object directly using this thing called the context, right? The context we talked about is this window into the database
that we get from that little use Core Data button right here. And this context is super important. Everything we do is going through that window of it, to the database. That's how we do everything in the database, but we're not gonna do that here because it might well be that this Airport that I'm trying to create here, which I'm essentially trying to create the Airport KSFO right, this Airport might already be in the database. So I kind of need a little function here, which I'm gonna call withICAO, which takes this String and looks it up in the database, and if it finds an Airport object, it gives it to me. And if it doesn't, it makes one, and not only makes one, but goes and fetches it from FlightAware too. So that's what this little function is gonna do. Now, how do we add a function to our Airport object that Xcode created for us? We're gonna do it with an extension. And we're just gonna extend this class,
this object-oriented class Airport, to have this static function, which lets us look an airport up by name. So let's go do that. I actually created that file here, Airport and blank file for now. And I'm gonna say extension of Airport, and here I'm gonna do this static ofunc withICAO. And it's gonna take that little special code that I was telling you about, and it's gonna return an Airport. And this is going to just look up that ICAO in Core Data. And if it finds it, return it,
if not, then we're going to create one and fetch from FlightAware. So that's what this function is going to do. So let's start with this, look up, still complaining about that, we won't worry about that for now. We want to look up this code in Core Data. So how do we look things up in Core Data to see if there's something there? We did this with a very important object called a FetchRequest, NSFetchRequest. In fact, so I'm gonna let request equal an NSFetchRequest now, NSFetchRequest is generic, it has a don't care, which is the kind of object you're trying to fetch.
Then you specify the entity name as a String. And this String is just whatever you put here as the name of your entity. So "Airline", "Airport" or "Flight". So this is how you create a FetchRequest. Now a FetchRequest is essentially a guide that we're going to use to have the database, know which Airport we want or which Airports, might be looking for multiple Airports. We might be looking for Airports by time zone, so we can get multiple Airports here, and this request is gonna let us specify which ones we want. So the request has two really important parts to it. One is called its predicate, and its predicate is the, which ones do you want?
And you create that with an object called an NSPredicate. And it kinda has a printf sort of feel to it, where you give it a format for what you wanna search and then any arguments that fit in there. So it's again pre-Swift. So it doesn't feel super Swift-y because it's printf-y, but you'll get used to it really easily. And for example, in our case, we want the ICAO to equal something. And what is that something? The ICAO that is passed to us up here, right?
This argument ICAO, I want my predicate to be, go look up this var, in the database, with this value. Then you can do things like, and another one of them or or something else equals something else. And there's even more powerful things where you can do pattern matching and begins with, and all kinds of things. This predicate object, obviously, if you're gonna do this Core Data you're gonna need to go look that up in the documentation and understand all the powerful things you can do to go figure out which objects you want from the database.
The other thing that we want to know here is the sortDescriptors. Now, the sortDescriptors are an Array of these things called NSSortDescriptor, and a SortDescriptor has two things. One is the name of the var you wanna sort by, then actually, if I'm looking for Airports, I'm gonna sort them by location, by the city that they're in. And then the second thing is whether you want them ascending in order or descending. And I do want this ascending. Now, why is this important to have this sortDescriptors here? That's because when we look up objects in the database, they're gonna come back as an Array, not as a Set, but as an Array.

Ask anything
We've read this whole study set, so questions about it get the best answers.