Database - Core Data
Entities - tables
Attributes - fields
NSPredicate - used to query compilation, filter data
Check - core data when creating app.
Click on xcdatamodeled
Create new entity
Go to the bottom and click +Entities.
Double click entity at the top and give it a name.
Add attribute at the right hand side.
Indicate the type.
At the right hand side of the screen, you will find the data model inspector, where you can provide more details for the attribute.
Click on the entity itself, on the right hand side, specify the codegen to be 'class definition'.
If you are storing an image, the type will be Binary Data.
Attributes - store in external data file (avoid huge use of space, can store pdf and other files as well)
Editor -> Create NSManagedSubClass
(If you change anything in the db, you need to add it manually into the classes)
Defining relationships
Storing data
import CoreData
//storing core data:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//key to let you access CoreData.
let newUser = NSEntityDescription.insertNewObject(forEntityName: "NameOfTable", into: context)
newUser.setValue("given value", forKey: "firstAttribute")
newUser.setValue("given value", forKey: "secondAttribute")
Getting Data
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "NameOfTable")
request.returnsObjectsAsFaults = false
do
{
let results = try context.fetch(request)
//check if result is empty
if results.count > 0
{
for result in results as! [NSManagedObject]
{
if let userName = result.value(forKey: "nameOfFirstAttribute") as? String
{
print(userName)
}
if let pswd = result.value(forKey: "nameOfSecondAttribute") as? String
{
print(pswd)
}
}
}
}
catch
{
}
Sorting the data
Place after:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "NameOfTable")
let sorter = NSSortDescriptor(key: "nameOfTheAttributeBeingSorted", ascending: true)
fetchRequest.sortDescriptors = [sorter]
Writing data to table view
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
implement functions:
numberOfSections
cellForRowAt
numberOfRowsInSection
Your entity can be used as a class, to be stored in an array:
var tasks: [Tasks] = []
In the above case, task is an entity.
numberOfRowsSelection:
return tasks.count
Create a new function to fetch the data:
func getData()
{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do
{
try tasks = context.fetch(Task.fetchRequest())
}catch{print(error.localizedDescription)}
}
cellForRowAt:
let cell = UITableViewCell()
//tells you which row
let oneTask = tasks[indexPath.row]
cell.textLabel?.text = oneTask.nameOfTask
//nameOfTask is the attribute
return cell
Swipe to delete
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if editingStyle == .delete
{
let taskToDelete = tasks[indexPath.row]
context.delete(taskToDelete)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
//fetch data again and reload table
do
{
try tasks = context.fetch(Task.fetchRequest())
}catch{}
}
ViewMyTasks.reloadData()
}
Attributes - fields
NSPredicate - used to query compilation, filter data
Check - core data when creating app.
Click on xcdatamodeled
Create new entity
Go to the bottom and click +Entities.
Double click entity at the top and give it a name.
Add attribute at the right hand side.
Indicate the type.
At the right hand side of the screen, you will find the data model inspector, where you can provide more details for the attribute.
Click on the entity itself, on the right hand side, specify the codegen to be 'class definition'.
If you are storing an image, the type will be Binary Data.
Attributes - store in external data file (avoid huge use of space, can store pdf and other files as well)
Editor -> Create NSManagedSubClass
(If you change anything in the db, you need to add it manually into the classes)
Defining relationships
Storing data
import CoreData
//storing core data:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//key to let you access CoreData.
let newUser = NSEntityDescription.insertNewObject(forEntityName: "NameOfTable", into: context)
newUser.setValue("given value", forKey: "firstAttribute")
newUser.setValue("given value", forKey: "secondAttribute")
//to store, need to do try catch:
do
{
try context.save()
print("saved")
}
catch
{
}
Getting Data
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "NameOfTable")
request.returnsObjectsAsFaults = false
do
{
let results = try context.fetch(request)
//check if result is empty
if results.count > 0
{
for result in results as! [NSManagedObject]
{
if let userName = result.value(forKey: "nameOfFirstAttribute") as? String
{
print(userName)
}
if let pswd = result.value(forKey: "nameOfSecondAttribute") as? String
{
print(pswd)
}
}
}
}
catch
{
}
Sorting the data
Place after:
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "NameOfTable")
let sorter = NSSortDescriptor(key: "nameOfTheAttributeBeingSorted", ascending: true)
fetchRequest.sortDescriptors = [sorter]
Writing data to table view
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{
implement functions:
numberOfSections
cellForRowAt
numberOfRowsInSection
Your entity can be used as a class, to be stored in an array:
var tasks: [Tasks] = []
In the above case, task is an entity.
numberOfRowsSelection:
return tasks.count
Create a new function to fetch the data:
func getData()
{
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
do
{
try tasks = context.fetch(Task.fetchRequest())
}catch{print(error.localizedDescription)}
}
In the above, tasks is an array used to store the data
Load the data into the table when it refreshes:
override ViewWillAppear:
getData()
tableView.reloadData()
let cell = UITableViewCell()
//tells you which row
let oneTask = tasks[indexPath.row]
cell.textLabel?.text = oneTask.nameOfTask
//nameOfTask is the attribute
return cell
Swipe to delete
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
if editingStyle == .delete
{
let taskToDelete = tasks[indexPath.row]
context.delete(taskToDelete)
(UIApplication.shared.delegate as! AppDelegate).saveContext()
//fetch data again and reload table
do
{
try tasks = context.fetch(Task.fetchRequest())
}catch{}
}
ViewMyTasks.reloadData()
}
Comments
Post a Comment