Swift Core Data Basics with easy sample project.
CoreData tutorial helps to create iPhone/iPad mobile application Project with CoreData.framework in Swift. I have created the sample project with clear comments and instructions.
- Necessary Environment.
- Shortcut Keys in Xcode.
- What is CoreData?
- Create Project with CoreData.
- Create Entities and Attributes in Model Layer.
- User Object life cycle : Create, Fetch, Update, Delete datas.
- Download Sample Project
- MAC system with above OS X (Yosimite) version 10.10.*
- Xcode version 7.*
- ⌘ = Command
- ⇧ = Shift
- ⌥ = Option/Alt
- ⌃ = Control
- ⇠⇢ = Left/Right Arrow Keys
- ⇡⇣ = Up/Down Arrow Keys
Core Data is a framework that you use to manage the model layer objects in your application. It provides generalized and automated solutions to common tasks associated with object life cycle and object graph management, including persistence.
Reference CoreData.framework
- Open Xcode.
- Create new project.(Fille > New > Project) - Shortcut Keys( ⇧ + ⌘ + N )
- Choose your template for you new project.
- Select Single View Application
- Select Language Swift
- Select Use Core Data Check box.
- Save it in Workspace.
- Go to the Workspace.
- Double Click ProjectName.xcodeproj and Open it in Xcode.
- Open ProjectName.xcdatamodeld
- Add Entite and Change name as you wish.
- Add Attribute for your Entity and Select Data Type for Attributes.
- Save it( ⌘ + S ).
- Create and Save object in local CoreData database.
Here's an example:
var User = [NSManagedObject]()
// Get AppDelegate Object
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
// Get Managed Context Object with help of AppDelegate.
let managedContext = appDelegate.managedObjectContext
// Create Entity Description with your entity name.
let entity = NSEntityDescription.entityForName("YOUR_ENTITE_NAME",
inManagedObjectContext:managedContext)
// Create Managed Objec with help of Entity and Managed Context.
let managedObject = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext: managedContext)
// Set the value for your represent attributes.
managedObject.setValue(VALUE, forKey: "YOUR_ATTRIBUTE")
// Handle the Exception.
do {
try managedContext.save() // Save Mangaged Context
User.append(managedObject) // Append your managedObject to the Database.
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
- Download as Zip file. Sample UviCoreData
- Clone with github URL. https://github.com/vigneshuvi/CoreData.git
Do you like this repo? Share it on Twitter, Facebook, Google+ or anywhere you like so that more of us can use it and help. Thanks!
Created by Vignesh