Core Data in swift (basics)

Lets Store data inside itself

Tony Wilson jesuraj
3 min readMar 24, 2021

Hi, i don’t want to waste my time by typing some paragraph because you not going to read it. Directly into the topic.

What is Core Data ?

you can use Core Data as a framework to save, monitor, alter, and filter data, within App

In this blog you will learn How to use the core data and save, fetch, delete single data, delete all the data

How to Start ?

Yes you know, Don’t forget to tick the “use core data” to import it.

then it will create a file named like <YourProjectName>.xcdatamodeld

click it, then press Add Entity

Then Name your Entity as your wish. add Attributes how much you want (I named TodoList)

here i just added one Attribute, you can add more Attribute as much you want (I named todoList — String)

So now your AppDelegate will have some code for CoreData will talk about that later (its Core Data Stack code).

let appDelegate = UIApplication.shared.delegate as! AppDelegatevar context = appDelegate.persistentContainer.viewContext

Because the container is set up in the AppDelegates, we would refer to it.

UIApplication.shared.delegate as! AppDelegate

is to refer it and

var context = appDelegate.persistentContainer.viewContext

To create a context from container

Now let’s save the data

Save data

let data = NSEntityDescription.insertNewObject(forEntityName: "Todolist", into: context!)data.setValue("String you need to add", forKey: "todolist")do {try context?.save()} catch {print("No error")}

BOOOM!! your data is saved But How..?

  • insertNewObject we going to save newObject here.
  • forEntityName: "YourEntityName"
  • setVale("your data"), forKey: "Your Attribute name". In forKey you need to enter your Attribute name not Entity name
  • context?.save() for asking.

Okay lets delete it :(

No i am going to fetch ;)

Fetch data

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Todolist")
request.returnsObjectsAsFaults = false

Creating request to fetch

do {let results = try context?.fetch(request)let count = results?.countif 0 < count ?? 0 {for todoList in results! as! [NSManagedObject] {if let todoList = todoList.value(forKey: "todolist") as? String {// i append in array, do whatever you want 
todoListArray.append(todoList)
}}}}

Delete All

You know what i’m, Doing Here

let managedContext = appDelegate.persistentContainer.viewContextlet DelAllReqVar = NSBatchDeleteRequest(fetchRequest: NSFetchRequest<NSFetchRequestResult>(entityName: "Todolist"))do {try managedContext.execute(DelAllReqVar)}catch {print(error)}

Delete single data

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Todolist")let pred = NSPredicate(format: "todolist=%@", "Data you need to delete")request.predicate = pred

Then

// call Fetch data here to fetch current datalet test = try context?.fetch(request)//then let objectDelete = test![0] as! NSManagedObjectcontext?.delete(objectDelete)

After deleting don’t forget to save

try context?.save()

Done for the day.

get the source code in Git . Created simple todo list app with core data you can refer it.

if any doubt or mistake you can reach me at twitter and shout,

நன்றி வணக்கம்

--

--