In this chapter, you used SQLite via Core Data. If you’re curious about what SQL commands Core Data is executing, you can use a command-line argument to log all communications with the SQLite database to the console. From the menu, choose Edit Scheme.... Select the Run Homepwner.app item and the Arguments tab. Add two arguments: -com.apple.CoreData.SQLDebug and 1.
Build and run the application again. Make sure the debug area and console are visible so you can see the SQL logging. Add a few locations and inventory items; then navigate around the application looking at various items.
Relationships are fetched in a lazy manner. When you fetch a managed object with relationships, the objects at the other end of those relationship are not fetched. Instead, Core Data uses faults. There are to-many faults (which stand in for sets) and to-one faults (which stand in for managed objects). So, for example, when the instances of Possession are fetched into your application, the instances of AssetType are not. Instead, fault objects are created that stand in for the AssetType objects until they are really needed.
An object fault knows what entity it is from and what its primary key is. So, for example, when you ask a fault that represents an asset type what its label is, you’ll see SQL executed that looks something like this:
SELECT t0.Z_PK, t0.Z_OPT, t0.ZLABEL FROM ZASSETTYPE t0 WHERE t0.Z_PK = 2
(Why is everything prefixed with Z_? I don’t know. What is OPT? I don’t know, but I would guess it is short for “optimistic locking”. These details are not important.) The fault is replaced, in the exact same location in memory, with a managed object containing the real data.
This lazy fetching makes Core Data not only easy to use, but also quite efficient.
What about to-many faults? Imagine that your application worked the other way: the user is presented with a list of AssetType objects to select from. Then, the possessions for that asset type are fetched and displayed. How would this work? When the assets are first fetched, each one has a set fault that is standing in for the NSSet of possession objects:
When the set fault is sent a message that requires the Possession objects, it fetches them and replaces itself with an NSSet:
Core Data is a very powerful and flexible persistence framework, and this chapter has been just a quick introduction to its capabilities. For more details, we strongly suggest that you read Apple’s Core Data Programming Guide. Here are some of the things we have not delved into:
3.129.210.102