second tutorial
https://www.youtube.com/watch?v=Fk4ier9Ip94
Core Data is poweful framework on iOS SDK that allows programmer to store and manage the data in Object Oriented way.
In this I’ll explain core data stack :
Core Data stack composed of following layers.
1. Managed Object Model
2. Manged Object Context
3. Data Model
4. Persistant Store Coordinator
5. Persistant Object Store
Managed Object Model : It’s collection of entity descrition, think about it as database schema and It represent our data model. NSManagedObjectModel class is use to implement it. (data model들의 구조들을 기술한다)
Managed Object Context : It keep track of all things we are doing with managed objects, it’s a like a virtual board.
Managed Object : Represent the entity we want to store in core data. In swift NSManagedObject instances are use to represent our data.(하나의 entity를 기술한다.)
Persistant Store : The object that represent actual db on disk. It is responsible to persist the data on disk. (data를 보관하는 하나의 store )
Persistant Store Coordinator : It’s the object that coordinate reading and writing of infofrom and to persistant store. It act as bridge between Managed object context and persistant store. (하나의 application에서도 여러개의 persistant store가 사용될수 있는데 이를 관리해주는 중간역할을 한다)
Core Data is poweful framework on iOS SDK that allows programmer to store and manage the data in Object Oriented way.
In this I’ll explain core data stack :
Core Data stack composed of following layers.
1. Managed Object Model
2. Manged Object Context
3. Data Model
4. Persistant Store Coordinator
5. Persistant Object Store
Managed Object Model : It’s collection of entity descrition, think about it as database schema and It represent our data model. NSManagedObjectModel class is use to implement it. (data model들의 구조들을 기술한다)
Managed Object Context : It keep track of all things we are doing with managed objects, it’s a like a virtual board.
Managed Object : Represent the entity we want to store in core data. In swift NSManagedObject instances are use to represent our data.(하나의 entity를 기술한다.)
Persistant Store : The object that represent actual db on disk. It is responsible to persist the data on disk. (data를 보관하는 하나의 store )
Persistant Store Coordinator : It’s the object that coordinate reading and writing of infofrom and to persistant store. It act as bridge between Managed object context and persistant store. (하나의 application에서도 여러개의 persistant store가 사용될수 있는데 이를 관리해주는 중간역할을 한다)
Core Data with Swift 4 for Beginners – XCBlog – Medium
original source : https://medium.com/xcblog/core-data-with-swift-4-for-beginners-1fc067cca707
Core Data is one of the most popular frameworks provided by Apple for iOS and macOS apps. Core data is used to manage the model layer object in our application. You can treat Core Data as a framework to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database. Core Data is using SQLite as it’s persistent store but the framework itself is not the database. Core Data does much more than databases like managing the object graphs, tracking the changes in the data and many more things. In this short post, we will see how to save and retrieve data using Core Data frameworks.
In order to demonstrate basics of the Core Data, let’s create single view iOS app with Core Data module selected.
Now that, we have created a demo project with Core Data support. There are two notable changes in this Xcode template we can easily observe which are
The Core Data Stack code inside the AppDelegate.swift has clear documentation in form of comments but in short, it set up the persistentContainer(data를 보관하는 방법, 장소 데이터베이스가 될수도 있다. sqlite가 될수도 있다.) and save the data if there are any changes. As AppDelegate is the first file that executes as soon as app launched, we can save and fetch the context the from the Core Data Stack(프로그램이 시작되면 제일 먼저 수행되는 것이 appdelegate화일이므로 이곳에서 콘테이너를 설정한다).
The new fileCoreDataDemo.xcdatamodeld acts as the model layer for the data that we want to save. We can easily ad the entity, attributes and relationships from the UI as like any other relational database.
Now that, let’s say we want to store the username, password and age attributes for the User entity. Select the CoreDataDemo.xcdatamodeld file and click on “Add Entity” (+) button and name the entity as Users. From the add username, password and age as String type attributes. The end result will look like this
Now that, we have modelled our data in the Users entity. It’s time to add some records and save it into the CoreData
The process of adding the records to Core Data has following tasks
Let’s do everything inside theViewController.swift and viewDidLoad() method. As we know that container is set up in the AppDelegates so we need to refer that container.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
We need to create a context from this container.
let context = appDelegate.persistentContainer.viewContext
Now let’s create an entity and new user records.
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
At last, we need to add some data to our newly created record for each keys using
newUser.setValue("Shashikant", forKey: "username")
newUser.setValue("1234", forKey: "password")
newUser.setValue("1", forKey: "age")
Now we have set all the values. The next step is to save them inside the Core Data
The methods for saving the context already exist in the AppDelegate but we can explicitly add this code to save the context in the Database. Note that, we have to wrap this with do try and catch block.
do {
try context.save()
} catch {
print("Failed saving")
}
At this stage, whenever we run our app the new entries will be added to the Core Data records.
The process of fetching the saved data from is very easy as well. It has the following task
We can fetch the data from our Users entity using following code.
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
}
} catch {
print("Failed")
}
This will print the value of username from the Core Data. That’s it! Now that, you have successfully saved and fetched data from Core Data.
Well, this isn’t enough to save and retrieve data, there are many complex things we can do with core data like modify, delete, tracking data changes, adding Predicates and complex relationships od databases. As you use more Core Data things get more complex.
The source code for this demo app is on Github as CoreDataDemo repository. You can clone the repo and play with Core Data.
$ git clone git@github.com:Shashikant86/CoreDataDemo.git
$ cd CoreDataDemo
$ open CoreDataDemo.xcodeproj/
Have Fun with Core Data!
Note: This article was originally published on personal blog a.k.a XCBlog here. Checkout my XCBlog site for more interesting things about iOS DevOps, Continuous Integration/Delivery here
Core Data with Swift 4 for Beginners – XCBlog – Medium
original source : https://medium.com/xcblog/core-data-with-swift-4-for-beginners-1fc067cca707
Core Data is one of the most popular frameworks provided by Apple for iOS and macOS apps. Core data is used to manage the model layer object in our application. You can treat Core Data as a framework to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database. Core Data is using SQLite as it’s persistent store but the framework itself is not the database. Core Data does much more than databases like managing the object graphs, tracking the changes in the data and many more things. In this short post, we will see how to save and retrieve data using Core Data frameworks.
In order to demonstrate basics of the Core Data, let’s create single view iOS app with Core Data module selected.
Now that, we have created a demo project with Core Data support. There are two notable changes in this Xcode template we can easily observe which are
The Core Data Stack code inside the AppDelegate.swift has clear documentation in form of comments but in short, it set up the persistentContainer(data를 보관하는 방법, 장소 데이터베이스가 될수도 있다. sqlite가 될수도 있다.) and save the data if there are any changes. As AppDelegate is the first file that executes as soon as app launched, we can save and fetch the context the from the Core Data Stack(프로그램이 시작되면 제일 먼저 수행되는 것이 appdelegate화일이므로 이곳에서 콘테이너를 설정한다).
The new fileCoreDataDemo.xcdatamodeld acts as the model layer for the data that we want to save. We can easily ad the entity, attributes and relationships from the UI as like any other relational database.
Now that, let’s say we want to store the username, password and age attributes for the User entity. Select the CoreDataDemo.xcdatamodeld file and click on “Add Entity” (+) button and name the entity as Users. From the add username, password and age as String type attributes. The end result will look like this
Now that, we have modelled our data in the Users entity. It’s time to add some records and save it into the CoreData
The process of adding the records to Core Data has following tasks
Let’s do everything inside theViewController.swift and viewDidLoad() method. As we know that container is set up in the AppDelegates so we need to refer that container.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
We need to create a context from this container.
let context = appDelegate.persistentContainer.viewContext
Now let’s create an entity and new user records.
let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)
At last, we need to add some data to our newly created record for each keys using
newUser.setValue("Shashikant", forKey: "username")
newUser.setValue("1234", forKey: "password")
newUser.setValue("1", forKey: "age")
Now we have set all the values. The next step is to save them inside the Core Data
The methods for saving the context already exist in the AppDelegate but we can explicitly add this code to save the context in the Database. Note that, we have to wrap this with do try and catch block.
do {
try context.save()
} catch {
print("Failed saving")
}
At this stage, whenever we run our app the new entries will be added to the Core Data records.
The process of fetching the saved data from is very easy as well. It has the following task
We can fetch the data from our Users entity using following code.
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
}
} catch {
print("Failed")
}
This will print the value of username from the Core Data. That’s it! Now that, you have successfully saved and fetched data from Core Data.
Well, this isn’t enough to save and retrieve data, there are many complex things we can do with core data like modify, delete, tracking data changes, adding Predicates and complex relationships od databases. As you use more Core Data things get more complex.
The source code for this demo app is on Github as CoreDataDemo repository. You can clone the repo and play with Core Data.
$ git clone git@github.com:Shashikant86/CoreDataDemo.git
$ cd CoreDataDemo
$ open CoreDataDemo.xcodeproj/
Have Fun with Core Data!
Note: This article was originally published on personal blog a.k.a XCBlog here. Checkout my XCBlog site for more interesting things about iOS DevOps, Continuous Integration/Delivery here