Skip to content

This app uses Core Data as its persistence API. There are two models in the Core Data schema namely, a User and Post entity.

Notifications You must be signed in to change notification settings

alexpaul/CoreData-Number-Facts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

13 Commits
 
 
 
 
 
 

Repository files navigation

CoreData-Number-Facts

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.

1. Vocabulary

  1. Entity - core data objects (classes)
  2. Attributes - class properties
  3. Relationships - connections between entities
  4. NSManagedObject - classes in Core Data inherit from NSManagedObject
  5. NSManagedObjectContext - the context is needed to commit any change to the persistence store
  6. NSPersistenceContainer - mangages NSManagedObjectContext's
  7. NSPredicate
  8. NSSortDescriptor

2. Accessing the context from the AppDelegate

private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

3. Fetching from the managed context

do {
  modelObjects = try context.fetch(Model.fetchRequest()) // all data
} catch {
  // error
}

4. Saving a new model to the NSManagedObjectContext

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 

5. Available types

  1. Undefined
  2. Integer 16
  3. Integer 32
  4. Integer 64
  5. Decimal
  6. Double
  7. Float
  8. String
  9. Boolean
  10. Date
  11. Boolean
  12. Date
  13. Binary Data (NSData)
  14. UUID
  15. URI
  16. Transformable (NSObject -> NSData)

6. Retrieving all objects from an NSSet (relationship)

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
*/

Additional Resources

  1. Saving an array to Core Data
  2. Apple - Configuring Attributes
  3. StackOverflow - Optionals in Core Data vs Swift

About

This app uses Core Data as its persistence API. There are two models in the Core Data schema namely, a User and Post entity.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages