Submit your appAboutContact

Swift core data: how to store objects

You'll learn how to store data in swift using the core data entity. You'll see how to use core data to save, read data and clear data from your iOS app. We'll see a simple example that shows how to define an entity in core data and how to save and read the data from it.

 Let's create a new Swift single view project. When filling the app title, be sure to turn on the core data feature.

 

When the swift project has been created, you can access to the file with the xcdatamodeld extension. Here you'll can define your entity name and structure. At first let's create the entity. Click on the add entity button (bottom). A new entity will be added. Let's tap on it (top-left) and put Data as an entity name. Finally with the Data entity selected, under the attributes section let's define our entity object. In this example we'll use an array of strings as an object. Tap on the plus button under the attributes section and set the name for the attributes to name and, as for the type, write string.

 

Now let's code. Open the ViewController.swift file and import the core data features by writing at the top:

import UIKit
import CoreData //import the CoreData

A core data object can be defined as

var name_list = [NSManagedObject]()

Let's define now the functions for clearing the data, storing new data, and reading the data.

Store data to a core data entity

The function for store the data to the core data entity is presented. The entity name in this case is defined as "Data" and we are storing the key called name.

func save(name:String)
{
	let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
	let managedContext = appDelegate.managedObjectContext!
	//Data is in this case the name of the entity
	let entity = NSEntityDescription.entityForName("Data",
					 inManagedObjectContext: managedContext)
	let options = NSManagedObject(entity: entity!,
                                      insertIntoManagedObjectContext:managedContext)

	options.setValue(name, forKey: "name")

	var error: NSError?
	if !managedContext.save(&error)
	{
		println("Could not save")
	}
	//uncomment this line for adding the stored object to the core data array
	//name_list.append(options) 
}
 

Read data from a core data entity

The function for reading data from core data is now defined. This function perform a query on the core data entity and all the results are taken.

func read()
{
	let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
	let managedContext = appDelegate.managedObjectContext!
	let fetchRequest = NSFetchRequest(entityName: "Data")

	var error: NSError?
	let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error)
			     as [NSManagedObject]?

	if let results = fetchedResults
	{
		for (var i=0; i < results.count; i++)
		{
			let single_result = results[i]
			let out = single_result.valueForKey("name") as String
			println(out)
 			//uncomment this line for adding the stored object to the core data array
			//name_list.append(single_result)
		}
	}
	else
	{
	println("cannot read")
	}
}
 

Clear data from a core data entity

The clear data from the core data entity function is defined. This function perform a query to take the whole data stored in core data and clear each element.

func clear_data()
{
	let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
	let managedContext = appDelegate.managedObjectContext!
	let fetchRequest = NSFetchRequest(entityName: "Data")
	var error: NSError?
	let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error)
			     as [NSManagedObject]?
	if let results = fetchedResults
	{
		for (var i=0; i < results.count; i++)
		{
			let value = results[i]
			managedContext.deleteObject(value)
			managedContext.save(nil)
		}
	}
}

 

Simple example

Let's do a simple example that shows how to use the previously defined functions. This will firstly clear all the data previously stored, save some name into the core data entity, and read the data from the core data entity.

override func viewDidLoad() {
	super.viewDidLoad()

	//clear everything
	clear_data()

	//save the data
	save("kaleidos blog")
	save("Put here what you want to store")

	read the data and display it in the debug
	read()
}

 UPDATE: download the example project for swift 2 here.

Leave a comment








Comments


- 25 November 2016 at 08:05
you are awesome. Love you bro.
- 14 September 2016 at 12:19
i have a json data and how store in core Data and display in tableview The following link contains JSON data.Using web services get data from this link and parse it and save it in core data(iOS) or sqlite (android).Get all users from data base show them in list view (each cell or list item should have image,first name and last name). Actions: If we delete a row from table,respect row in database table should also be deleted. If we click on any row, it should take us to next screen there we have to show all info of selected row. http://colorssoftware.com/ionic/generated.json
- 16 June 2016 at 15:43
i got warning: CoreData: warning: Unable to load class named 'Swift_Variable_Declaration.Logitem' for entity 'Logitem'. Class not found, using default NSManagedObject instead. project name = Swift_Variable_Declaration entity = Logitem
Andrea - 22 June 2016 at 08:51
Can you please send me your swift project to let me directly try and test it?
- 09 October 2015 at 09:30
I updated my Xcode version as 7 and i want to save the data in viewDidLoad(). It shows error as "Call can throw, but it is not marked with 'try' and the error is not handled". Thanks in advance.
Andrea - 09 October 2015 at 19:04
Hi, here is the project for swift 2. Hope it helps: http://www.kaleidosblog.com/tutorial/swift_core_data.zip





Submit your appAboutContactPrivacy