Based on Xcode 7.2(7C68)
AppDelegate.swift
to use conveniently in the future:let managedContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
Get the entity out from ManagedContext: let entity = NSEntityDescription.entityForName("Entity", inManagedObjectContext: managedContext)
Decalre a new record:
// "Entity" in the next line is the name of NSManagedObject subclass<br></br>
let newdiary = Entity(entity: entity!, insertIntoManagedObjectContext:managedContext)
newdiary.day = Int(day.text!)<br></br>
newdiary.des = "This is Description."<br></br>
newdiary.fav = true<br></br>
newdiary.id = 20160117<br></br>
newdiary.img = nil // Here supposed to be a Date variable.<br></br>
newdiary.month = 1<br></br>
newdiary.year = 2016
do {<br></br>
try managedContext.save()<br></br>
} catch {<br></br>
fatalError("Failure to save context: \(error)")<br></br>
}
var fetchedDay : NSFetchedResultsController!<br></br>
var fetchedDes : NSFetchedResultsController!
Create a fetch request (target entity is “Entity”): let fetchRequest = NSFetchRequest(entityName:"Entity")
Sort the fetch result (ascending by the column “day”): fetchRequest.sortDescriptors = [NSSortDescriptor(key: "day", ascending: true)]
Init two NSFetchResultsController:
fetchedDay = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext,sectionNameKeyPath: "day", cacheName: nil)<br></br>
fetchedDes = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedContext,sectionNameKeyPath: "des", cacheName: nil)
try self.fetchedDay.performFetch()
try self.fetchedDes.performFetch()
do {
......
} catch {
fatalError("Failure to save context: \(error)")
}
var day = fetchedDay.sections![X].name<br></br>
var des = fetchedDes.sections![X].name