This app uses Core Data as its persistence API.
There are two models in the Core Data schema namely, a User and Post entity.
Core Data is an object graph not a database.
- Entity - core data objects (classes)
- Attributes - class properties
- Relationships - connections between entities
- NSManagedObject - classes in Core Data inherit from NSManagedObject
- NSManagedObjectContext - the context is needed to commit any change to the persistence store
- NSPersistenceContainer - mangages NSManagedObjectContext's
- NSPredicate
- NSSortDescriptor
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContextdo {
modelObjects = try context.fetch(Model.fetchRequest()) // all data
} catch {
// error
}Sample code for adding a new model object (record) to Core Data
let model = Model(entity: Model.entity(), insertInto: context)
model.propertyName = someData
appDelegate.saveContext() // save the new model object to the managed object content
// update your collection ui as needed - Undefined
- Integer 16
- Integer 32
- Integer 64
- Decimal
- Double
- Float
- String
- Boolean
- Date
- Boolean
- Date
- Binary Data (NSData)
- UUID
- URI
- Transformable (NSObject -> NSData)
Below we are retrieving all the user's posts.
// get a specific user's posts
let posts = user.posts?.allObjects as? [Post] ?? []
dump(posts)
/*
▿ 1 element
- <CoreData_Number_Facts.Post: 0x6000037ed400> (entity: Post; id: 0x920d371640595395 <x-coredata://C8C1F783-B07D-4670-A26B-4026C71513C7/Post/p2>; data: {
location = nil;
number = "2912.8";
title = "Distance from New York to California (in miles)";
user = "0x920d371640555397 <x-coredata://C8C1F783-B07D-4670-A26B-4026C71513C7/User/p1>";
}) #0
- super: NSManagedObject
- super: NSObject
*/