Detailed explanation of adding, deleting, modifying, and querying iOS CoreData, ioscoredata

Source: Internet
Author: User

Detailed explanation of adding, deleting, modifying, and querying iOS CoreData, ioscoredata

Recently, I have been studying CoreData because I have learned and sorted it out for future use and reference. Currently, the project is developed using the Swift language. So we sorted out the Swift version, and I gave up OC. Although Swift3 already exists, the current version is Swift2. In Swift 3, there are some new features. You need to make other adjustments, and you will have time to sort them out later.

There are two ways to inherit CoreData:

Integration during project Creation

This method is automatically inherited in AppDelegate. You need to use the UIApplication method to obtain AppDelegate and get Conext. I don't like this method. I don't like AppDelegate too much code together. I sorted it out.

 

Separate the Code inherited from CoreData to create a single-instance project structure.

Project File description

The core file of CoreData is

1. XPStoreManager (single case class for managing CoreData)

2. CoredataDemo. xcdatamodeld (CoreData data model file)

3. Student + CoreDataProperites. swift and Student. swift (students)

4. ViewController. swift and Main. storyboard are sample codes.

Detailed code

1. XPStoreManager. swift

CoreData Data Management Singleton class

/// XPStoreManager. swift // CoreDataDemo // Created by xiaopin on 16/9/16. // Copyright©2016 xiaopin.cnblogs.com. all rights reserved. // import CoreData // local database management class: it is written in AppDelegate by default. you can separate the class XPStoreManager {// use the single-sample method static let program instance = XPStoreManager () private init () {} // MARK:-Core Data stack lazy var applicationDocumentsDirectory: NSURL = {// The directory the application uses to store the Core Data store file. this code uses a directory named "com. pinguo. coreDataDe Mo "in the application's documents ents Application Support directory. let urls = NSFileManager. defaultManager (). URLsForDirectory (. documentDirectory, inDomains :. userDomainMask) print ("\ (urls [urls. count-1]) ") return urls [urls. count-1]} () lazy var managedObjectModel: NSManagedObjectModel = {// The managed object model for the application. this property is not optional. it is a fatal error for the appl Ication not to be able to find and load its model. let modelURL = NSBundle. mainBundle (). URLForResource ("CoreDataDemo", withExtension: "momd ")! Return NSManagedObjectModel (contentsOfURL: modelURL )!} () Lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {// The persistent store coordinator for the application. this implementation creates and returns a coordinator, having added the store for the application to it. this property is optional since there are legitimate error conditions that cocould cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator (managedObjectModel: self. managedObjectModel) let url = self. applicationDocumentsDirectory. URLByAppendingPathComponent ("SingleViewCoreData. sqlite ") var failureReason =" There was an error creating or loading the application's saved data. "do {try coordinator. addPersistentStoreWithType (NSSQLiteStoreType, configuration: nil, URL: url, options: nil)} catch {// Report any error we got. var dict = [String: AnyObject] () dict [NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict [Failed] = failureReason dict [Failed] = error as NSError let wrappedError = NSError (domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. NSLog ("Unresolved error \ (wrappedError), \ (wrappedError. userInfo) ") abort ()} return coordinator} () lazy var managedObjectContext: NSManagedObjectContext = {// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application .) this property is optional since there are legitimate error conditions that cocould cause the creation of the context to fail. let coordinator = self. persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext (concurrencyType :. mainQueueConcurrencyType) managedObjectContext. persistentStoreCoordinator = coordinator return managedObjectContext} () // MARK:-Core Data Saving support func saveContext () {if managedObjectContext. hasChanges {do {try managedObjectContext. save ()} catch {// Replace this implementation with code to handle the error appropriately. // abort () causes the application to generate a crash log and terminate. you shoshould not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog ("Unresolved error \ (nserror), \ (nserror. userInfo) ") abort ()}}}}

  

2. AppDelegate. swift

Add a line of code to the number of rows, exit and save the code.

func applicationWillTerminate(application: UIApplication) {        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.        // Saves changes in the application's managed object context before the application terminates.        XPStoreManager.shareInstance.saveContext()    }

  

3. Student. swift

Added, deleted, modified, and queried student objects.

/// Student. swift // CoreDataDemo /// Created by cdmac on 16/9/12. // Copyright©2016 xiaopin.cnblogs.com. all rights reserved. // import Foundationimport CoreDataclass Student: NSManagedObject {// Insert code here to add functionality to your managed object subclass/* generally involves adding, deleting, modifying, and querying a single object, paging query (all, conditional query, sorting), whether an object exists, batch addition, batch modification * // determine whether an object exists, the obj parameter is the dictionary class func exsitsObject (obj: [String: String]) of the current Attribute-> Bool {// gets the context of the management data object let context = XPStoreManager. specified instance. managedObject Context // declare a Data Request let fetchRequest = NSFetchRequest (entityName: "Student ") // combine the filter parameters let stuId = obj ["stuId"] let name = obj ["name"] // method 1 let predicate1 = NSPredicate (format: "stuId = % @", stuId !) Let predicate2 = NSPredicate (format: "name = % @", name !) // Merging filter conditions // or, and, not, which means: or non-. If you know database, you can easily understand let predicate = NSCompoundPredicate (orPredicateWithSubpredicates: [predicate1, predicate2]) // let predicate = NSCompoundPredicate (andPredicateWithSubpredicates: [predicate1, predicate2]) fetchRequest. predicate = predicate // method 2 // fetchRequest. predicate = NSPredicate (format: "stuId = % @ or name = % @", stuId !, Name !) // FetchRequest. predicate = NSPredicate (format: "stuId = % @ and name = % @", stuId !, Name !) Do {let fetchObjects: [AnyObject]? = Try context.exe cuteFetchRequest (fetchRequest) return fetchObjects ?. Count> 0? True: false} catch {fatalError ("exsitsObject \ (error)")} return false} // Add an object. The obj parameter is the dictionary class func insertObject (obj: [String: String])-> Bool {// if an object exists, return if exsitsObject (obj) {return false} // obtain the managed data context object let context = XPStoreManager. specified instance. managedObjectContext // create the student object let stu = NSEntityDescription. insertNewObjectForEntityForName ("Student", inManagedObjectContext: context) As! Student // object Value assignment let sexStr: string if obj ["sex"] = "male" {sexStr = "1"} else {sexStr = "0"} let numberFMT = NSNumberFormatter () numberFMT. numberStyle =. noStyle stu. stuId = numberFMT. numberFromString (obj ["stuId"]!) Stu. name = obj ["name"] stu. createtime = NSDate () stu. sex = numberFMT. numberFromString (sexStr) stu. classId = numberFMT. numberFromString (obj ["classId"]!) // Save do {try context. save () print ("saved successfully! ") Return true} catch {fatalError (" cannot be saved: \ (error) ")} return false} // Delete the object class func deleteObject (obj: Student) -> Bool {// obtain the managed data context object let context = XPStoreManager. specified instance. managedObjectContext // Method 1: for example, if the list is already an object obtained from the database, you can directly call the default Delete method context of CoreData. deleteObject (obj) XPStoreManager. specified instance. saveContext () // Method 2: Query an object using the obj parameter such as id and name, and delete the object from the database. // code: slightly return true} // more New object class func updateObject (obj: [String: String])-> Bool {// obj parameter description: The field information to be updated for the current object. The unique identifier is required, other options include let context = XPStoreManager. specified instance. managedObjectContext let oid = obj ["stuId"] let student: Student = self. fetchObjectById (Int (oid !)!)! As! Student // traverse the parameter, and then replace the corresponding parameter let numberFMT = NSNumberFormatter () numberFMT. numberStyle =. noStyle for key in obj. keys {switch key {case "name": student. name = obj ["name"] case "classId": student. classId = numberFMT. numberFromString (obj ["classId"]!) Default: print ("if other parameters need to be modified, similar to") }// execute the update operation do {try context. save () print ("Update successful! ") Return true} catch {fatalError (" cannot be saved: \ (error) ")} return false} // query object class func fetchObjects (pageIndex: Int, pageSize: Int) -> [AnyObject]? {// Obtain the managed data context object let context = XPStoreManager. specified instance. managedObjectContext // request for declaring data let fetchRequest: NSFetchRequest = NSFetchRequest (entityName: "Student") fetchRequest. fetchLimit = pageSize // the size of each page. fetchRequest. fetchOffset = pageIndex * pageSize // page/set query conditions: see exsitsObject // let predicate = NSPredicate (format: "id = '1 '","") // fetchRequest. predicate = predicate // set the sorting // let stuI in descending order by student ID DSort = NSSortDescriptor (key: "stuId", ascending: false) // let nameSort = NSSortDescriptor (key: "name", ascending: true) let sortDescriptors: [NSSortDescriptor] = [stuIdSort, nameSort] fetchRequest. sortDescriptors = sortDescriptors // query operation do {let fetchedObjects: [AnyObject]? = Try context.exe cuteFetchRequest (fetchRequest) // traverse the query result/* for info: Student in fetchedObjects! [Student] {print ("id = \ (info. stuId) ") print (" name = \ (info. name) ") print (" sex = \ (info. sex) ") print (" classId = \ (info. classId) ") print (" createTime = \ (info. createtime) ") print (" ------------------- ")} */return fetchedObjects} catch {fatalError (" cannot save: \ (error )")} return nil} // query the ID of an object class func fetchObjectById (oid: Int)-> AnyObject? {// Obtain the context object let context = XPStoreManager. specified instance. managedObjectContext // create the query object let fetchRequest: NSFetchRequest = NSFetchRequest (entityName: "Student") // construct the parameter fetchRequest. predicate = NSPredicate (format: "stuId = % @", String (oid) // run the code and return the result do {let results: [AnyObject]? = Try context.exe cuteFetchRequest (fetchRequest) if results ?. Count> 0 {return results! [0]} catch {fatalError ("Fatal error of querying an object: \ (error)")} return nil }}

  

4. ViewController. swift

Specific use:

/// ViewController. swift // CoreDataDemo /// Created by cdmac on 16/9/11. // Copyright©2016 pinguo. All rights reserved. // import UIKitlet cellIdentifiler = "ReuseCell" class ViewController: UIViewController {@ IBOutlet weak var txtNo: UITextField! @ IBOutlet weak var txtName: UITextField! @ IBOutlet weak var txtSex: UITextField! @ IBOutlet weak var txtClassId: UITextField! @ IBOutlet weak var tableView: UITableView! Var dataArray: [AnyObject]? Override func viewDidLoad () {super. viewDidLoad () // Do any additional setup after loading the view, typically from a nib. self. dataArray = Student. fetchObjects (0, pageSize: 20) self. tableView. reloadData ()} override func didReceiveMemoryWarning () {super. didReceiveMemoryWarning () // Dispose of any resources that can be recreated .} @ IBAction func addAction (sender: AnyObject) {var dic = [String: S Tring] () dic ["stuId"] = txtNo. text dic ["name"] = txtName. text dic ["sex"] = txtSex. text dic ["classId"] = txtClassId. text if Student. insertObject (dic) {print ("added successfully") self. dataArray = Student. fetchObjects (0, pageSize: 20) self. tableView. reloadData ()} else {print ("failed to add") }}@ IBAction func updateAction (sender: AnyObject) {var dic = [String: String] () dic ["stuId"] = txtNo. text dic ["name"] = txtName. tex T // dic ["sex"] = txtSex. text dic ["classId"] = txtClassId. text if Student. updateObject (dic) {print ("updated successfully") self. dataArray = Student. fetchObjects (0, pageSize: 20) self. tableView. reloadData ()} else {print ("update failed") }}extension ViewController: UITableViewDelegate, UITableViewDataSource {// Number of func numberOfSectionsInTableView (tableView: UITableView) -> Int {return 1} // number of rows in each group func tableView (tableVie W: UITableView, numberOfRowsInSection section: Int)-> Int {if self. dataArray! = Nil & self. dataArray ?. Count> 0 {return self. dataArray !. Count} return 0} // height func tableView (tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath)-> CGFloat {return 50} // The cell loads func tableView (tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath)-> UITableViewCell {let cell = tableView. dequeueReusableCellWithIdentifier (cellIdentifiler) let stu: Student = self. dataArray! [IndexPath. row]! Student let label1: UILabel = cell ?. ContentView. viewWithTag (10001)! UILabel let label2: UILabel = cell ?. ContentView. viewWithTag (10002)! UILabel var sexStr = "male" if stu. sex ?. IntValue! = 1 {sexStr = ""} label1.text = "\ (stu. stuId !) \ (Stu. name !) \ (SexStr) \ (stu. classId !) "Label2.text =" http://xiaopin.cnblogs.com "return cell!} // Select func tableView (tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {} func tableView (tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {return true} func tableView (tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {if editingStyle =. delete {// get the current object let studen T: Student = self. dataArray! [IndexPath. row]! Student // Delete the local storage Student. deleteObject (student) // refresh the data source self. dataArray ?. RemoveAtIndex (indexPath. row) // self. dataArray = Student. fetchObjects (0, pageSize: 20) // Delete the tableView cell. deleteRowsAtIndexPaths ([indexPath], withRowAnimation :. automatic)} func tableView (tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath)-> UITableViewCellEditingStyle {return. delete} func tableView (tableView: UITableView, titleForDeleteConfirmationButtonForRowAtIndex Path indexPath: NSIndexPath)-> String? {Return "delete "}}

  

Run

Source code download: CoreDataDemo.zip

 

Original article. reposted the famous source! Thank you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.