Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 


Oak Ridge, TN, 37830
United States

Swift-Snips

Coredata CRD

Wade Cantley

Be sure that project uses core data so that many of the delegate functions are pulled into AppDelegate.

1) Import the framework
2) setup the entity reference
3) Read with a predicate (search param)
4) Insert
5) Delete
6) Save the changes


1) Import the framework

import CoreData

2) setup the entity reference

This is used under every circumstance of coredata.

Here we are setup to interface with the entity (table) called “Users” which contains two text fields “username” and “password"

// Setup this variable as the appDelegate
        var appDel = (UIApplication.sharedApplication().delegate as AppDelegate)
       
        // Setup the managed object context
        var context = appDel.managedObjectContext
   

3) Read with a predicate (search param)

let myEntity: NSString = "Users"
var request = NSFetchRequest(entityName: myEntity)
request.returnsObjectsAsFaults = false
        
// Setup the predicate for the request which is what we are searching by.
// in this example we are searching the field “username” for records that have “chris” in it.
// Using a predicate is optional.  You could read all if you wanted to.
request.predicate = NSPredicate(format: "username = %@", “chris")

// Now execute, and put the results into a variable
var results = context.executeFetchRequest(request, error: nil)

// This gets the first object in the set of results which is at position 0
var res = results[0] as NSManagedObject
            
// Now we display it
println("\(res)”)

4) Insert

// Setup the reference to the database object to be managed
let myEntity: NSString = "Users"
        var newUser = NSEntityDescription.insertNewObjectForEntityForName(myEntity, inManagedObjectContext: context) as NSManagedObject


// Change the fields in the target database object
newUser.setValue(“chris", forKey: "username")
newUser.setValue(“mypassword", forKey: "password")
       
// Save (without error catching)
context.save(nil)

5) Delete

This starts like a read, but eventually we loop through the records, find the ones that have the value we are looking

for and then delete the record.

// setup request
let myEntity: NSString = "Users"
var request = NSFetchRequest(entityName: myEntity)
request.returnsObjectsAsFaults = false

// In this example we are searching for all records that have “chris” in them.
request.predicate = NSPredicate(format: "username = %@", “chris")

// execute the fetch and put it into a variable.
var results = context.executeFetchRequest(request, error: nil)

// Loop over the results and delete each object that came back.
for res in results{
     context.deleteObject(res as NSManagedObject)
}

// Save (without error catching)
context.save(nil)