Using Core Data in Swift
As of Xcode 7b6, generating NSManagedObject subclasses for Swift in Xcode for an entity with a to-many relationship will generate a property of the. Swift started with a noble goal, but it went off the rails when we were. My goal with this blog entry is to help get you set up to create NSManagedObject subclasses in Swift for the Entities in your Core Data model. In this tutorial, you'll write your very first Core Data app. . Your goal for the HitList app is simple: persist the names you enter so they're In Core Data, relationships between two entities are called to-one relationships, while . you customize your own managed object subclasses to store and validate data.
The array is in memory but if you force quit the app or reboot your device, your hit list will be wiped out. Core Data provides persistence, meaning it can store data in a more durable state so it can outlive an app re-launch or a device reboot. This will take you back to the familiar app grid on the home screen: From the home screen, tap the HitList icon to bring the app back to the foreground. The names are still on the screen. When you tap the Home button, the app currently in the foreground goes to the background.
When this happens, the operating system flash-freezes everything currently in memory, including the strings in the names array. Apple introduced these advances in multitasking back in iOS 4. They create a seamless experience for iOS users but add a wrinkle to the definition of persistence for iOS developers.
Are the names really persisted? If you had completely killed the app in the fast app switcher or turned off your phone, those names would be gone. You can verify this as well. With the app in the foreground, enter the fast app switcher. From here, flick the HitList app snapshot upwards to terminate the app.Swift: FB Messenger - Core Data Entities: Create, Read, Delete (Ep 2)
After you remove the app from the app switcher, there should be no trace of HitList in living memory no pun intended. Verify the names are gone by returning to the home screen and tapping on the HitList icon to trigger a fresh launch.
All that matters is the names are still there when the app comes back! So the real test of persistence is whether your data is still there after a fresh app launch. Your goal for the HitList app is simple: The first step is to create a managed object model, which describes the way Core Data represents data on disk.
For a comprehensive list of Core Data classes, check out the Core Data framework reference in the documentation browser. As you can see, Xcode has a powerful Data Model editor: The Data Model editor has a lot of features you can explore later. Click on Add Entity on the lower-left to create a new entity.
Double-click the new entity and change its name to Person, like so: You may be wondering why the model editor uses the term Entity. An entity is a class definition in Core Data. The classic example is an Employee or a Company. In a relational database, an entity corresponds to a table.
Why are to-many Core Data relationships represented as optionals?
An attribute is a piece of information attached to a particular entity. In a database, an attribute corresponds to a particular field in a table.
A relationship is a link between multiple entities. In Core Data, relationships between two entities are called to-one relationships, while those between one and many entities are called to-many relationships. For example, a Manager can have a to-many relationship with a set of employees, whereas an individual Employee will usually have a to-one relationship with his manager.
Likewise, attributes and relationships sound a lot like properties. You can think of a Core Data entity as a class definition and the managed object as an instance of that class.
Now you know what an attribute is, you can add an attribute to Person object created earlier. In Core Data, an attribute can be of one of several data types. Next, replace the names property definition with the following: It now holds instances of NSManagedObject rather than simple strings.
NSManagedObject represents a single object stored in Core Data; you must use it to create, edit, save and delete from your Core Data persistent store.
Why are to-many Core Data relationships represe |Apple Developer Forums
It can take the form of any entity in your Data Model, appropriating whatever attributes and relationships you defined. Instead of matching cells with the corresponding string in the model array, you now match cells with the corresponding NSManagedObject.
Note how you grab the name attribute from the NSManagedObject. String Why do you have to do this? Xcode complains because save name: Think of saving a new managed object to Core Data as a two-step process: Remember, this only happens if you check the Use Core Data checkbox at the beginning. This default managed object context lives as a property of the NSPersistentContainer in the application delegate.
To access it, you first get a reference to the app delegate. You create a new managed object and insert it into the managed object context. You may be wondering what an NSEntityDescription is all about. Recall earlier, NSManagedObject was called a shape-shifter class because it can represent any entity. An entity description is the piece linking the entity definition from your Data Model with an instance of NSManagedObject at runtime. With an NSManagedObject in hand, you set the name attribute using key-value coding.
You must spell the KVC key name in this case exactly as it appears in your Data Model, otherwise, your app will crash at runtime. You commit your changes to person and save to disk by calling save on the managed object context. Note save can throw an error, which is why you call it using the try keyword within a do-catch block. Finally, insert the new managed object into the people array so it shows up when the table view reloads.
Some of the code here, such as getting the managed object context and entity, could be done just once in your own init or viewDidLoad then reused later. Build and run the app, and add a few names to the table view: If the names are actually stored in Core Data, the HitList app should pass the persistence test. With the app in the foreground, go to the fast app switcher and then terminate it.
From Springboard, tap the HitList app to trigger a fresh launch. The table view is empty: You saved to Core Data, but after a fresh app launch, the people array is empty! Fetching from Core Data To get data from your persistent store into the managed object context, you have to fetch it.
Before you can do anything with Core Data, you need a managed object context. Fetching is no different! By marking an entity as abstract in the Entity pane of the Data Model inspector, you are informing Core Data that it will never be instantiated directly. Entity Inheritance Entity inheritance works in a similar way to class inheritance; and is useful for the same reasons.
If you have a number of entities that are similar, you can factor the common properties into a superentity, also known as a parent entity.
Rather than specifying the same properties in several entities, you can define them in one entity, and the subentities inherit them.
For example, you might define a Person entity with attributes firstName and lastName, and subentities Employee and Customer, which inherit those attributes. An example of this layout is shown in Figure Display the layout diagram by clicking the Editor Style buttons in the lower-right corner. In many cases, you also implement a custom class to correspond to the entity from which classes representing the subentities also inherit. Rather than implementing business logic common to all the entities several times over, you implement them in one place and they are inherited by the subclasses.
Note Be careful with entity inheritance when working with SQLite persistent stores. All entities that inherit from another entity exist within the same table in SQLite. This factor in the design of the SQLite persistent store can create a performance issue. Among other features, each property has a name and a type. Core Data does track changes you make to transient properties, so they are recorded for undo operations.
You use transient properties for a variety of purposes, including keeping calculated values and derived values. Note If you undo a change to a transient property that uses nonmodeled information, Core Data does not invoke your set accessor with the old value — it simply updates the snapshot information. You can specify that an attribute is optional—that is, it is not required to have a value. In general, however, avoid doing so, especially for numeric values.
Typically, you can get better results using a mandatory attribute with a default value—defined in the attribute—of 0. Moreover, NULL in a database is not equivalent to an empty string or empty data blob.
Relationships and Fetched Properties To define a relationship, select it in the Core Data model editor, and specify values in the Relationship pane of the Data Model inspector; Relationship in the Data Model inspector. Figure Relationship pane in the Data Model inspector Core Data supports to-one and to-many relationships, and fetched properties. Fetched properties represent weak, one-way relationships. The Type pop-up menu defines whether the relationship is a to-one type relationship or a to-many type relationship.
Relationships are defined from one direction at a time. To create a many-to-many relationship, you would need to create two to-many relationships and then set them up as inverses of each other.
The Destination pop-up menu defines what object or objects is returned when the relationship is accessed in code. If the relationship is defined as to-one, a single object or nil if the relationship can be optional is returned.