Brief introduction
This article documents some of the basics of using Swift to manipulate coredata in IOS, and because of the lack of documentation, it's basically the result of self-experimentation, and errors and omissions are unavoidable, please understand.
Part of the content borrowed from Tim Roadley's "Learning.Core.Data.for.iOS (2013.11)", this book mainly introduces OBJC CoreData.
Create a new XCode project
- Create a new XCode project.
- Create an Empty application
- Fill in the information about the project, such as setting the project name to: Swiftcoredatasimpledemo, note that the language is Swift, and tick the use Core Data.
- Select the directory where the project is stored
- Create a new project as shown in
Modifying the Core Data Model
- Select the Swiftcoredatasimpledemo.xcdatamodeld file, currently empty.
- Create two Entity, named Family and Member, respectively.
- Before generating the model file, we can create a Group named models, which holds the generated model files.
- After selecting an Entity for the Swiftcoredatasimpledemo.xcdatamodeld file, you can find the Create Nsmanagedobject subclass in the Editor menu, select this project, and start creating the model file.
- Following the wizard, complete the model creation, you can select all the Entity and specify the storage location as the models Group we just created.
- Before the end, XCode pops up a dialog asking if you want to create a library file Swiftcoredatasimpledemo-bridging-header.h for Swift and OBJC to work together, and of course choose Yes.
Once the build is complete, you will be able to see the new model file in Project. At this point, Swiftcoredatasimpledemo-bridging-header.h is still empty, and we need to add the header files that need to be accessed by Swift. The results are as follows:
#import "Family.h"#import "Member.h"
Modify Appdelegate
Like the new OBJC App, a new project adds code that operates coredata to the Appdelegate.swift file. In order to make the code more concise and clear, we extracted this part of the code and moved it to Coredatahelper.swift.
- Open the original Appdelegate.swift, and in the latter part of the program, you can see the code associated with the Operation CoreData. as shown in.
- Create a new Coredatahelper.swift file. The modified file name is Coredatahelper.
- In Appdelegate.swift
func saveContext () , and later, in the code, move to the Coredatahelper.swift file. And make minor adjustments to it, will be used in the project name Commission constant, placed in the front of the coredatahelper, so that in the future if the need to use Coredatahelper in the history project, it is very convenient.
The Coredatahelper.swift code after completion is as follows:
coredatahelper.swift//swiftcoredatasimpledemo////Created by Chenhao on 14-6-7.//Copyright (c) 2014 Chenhao. All rights reserved.//import Coredataclass coredatahelper{let storeName = ' Swiftcoredatasimpledemo ' let Storefilena me = "swiftcoredatasimpledemo.sqlite"//#pragma mark-core Data stack//Returns the managed object context for th E application. If the context doesn ' t already exist, it's created and bound to the persistent store coordinator for the application. var Managedobjectcontext:nsmanagedobjectcontext {if!_managedobjectcontext {let coordinator = Self.persist Entstorecoordinator if coordinator! = Nil {_managedobjectcontext = Nsmanagedobjectcontext () _managedobjectcontext!. persistentstorecoordinator = coordinator}} return _managedobjectcontext! } var _managedobjectcontext:nsmanagedobjectcontext? = nil//Returns the managed object model for the application. If the model doesn ' t already exist, it is created from the application ' s model. var Managedobjectmodel:nsmanagedobjectmodel {if!_managedobjectmodel {let Modelurl = Nsbundle.mainbundle (). Urlforresource (StoreName, withextension: "MOMD") _managedobjectmodel = Nsmanagedobjectmodel (contentsofurl:modelurl )} return _managedobjectmodel! } var _managedobjectmodel:nsmanagedobjectmodel? = nil//Returns the persistent store coordinator for the application. If the coordinator doesn ' t already exist, it's created and the application ' s store added to it. var Persistentstorecoordinator:nspersistentstorecoordinator {if!_persistentstorecoordinator {let StoreURL = Self.applicationDocumentsDirectory.URLByAppendingPathComponent (Storefilename) var error:nserror? = Nil _persistentstorecoordinator = Nspersistentstorecoordinator (ManagedObjectModel:self.managedObjectModel) If _persistentstorecoordinator!. AddpersistenTstorewithtype (Nssqlitestoretype, Configuration:nil, Url:storeurl, Options:nil, error: &error) = = Nil { /* Replace This implementation with code to handle the error appropriately. Abort () causes the application to generate a crash log and terminate. You should don't use the This function in a shipping application, although it could be useful during. Typical reasons for a error here include: * The persistent store was not accessible; * The schema for the persistent store was incompatible with current managed object model. Check the error message to determine what the actual problem is. If the persistent store is not accessible, there are typically something wrong with the file path. Often, a file URL is pointing into the application ' s resources directory instead of a writeable directory. If you encounter the schema incompatibility errors during development, you can reduce their frequEncy by: * Simply Deleting the existing Store:NSFileManager.defaultManager (). Removeitematurl (Storeu RL, Error:nil) * Performing automatic lightweight migration by passing the following dictionary as the options Parameter: [Nsmigratepersistentstoresautomaticallyoption:true, Nsinfermappingmodelautomaticallyoption:true} Lightweight migration would only work for a limited set of schema changes; Consult "Core Data Model Versioning and Data Migration Programming Guide" for details. *///PRINTLN ("Unresolved error \ (error), \ (error.userinfo)") Abort ()}} return _persistentstorecoordinator! } var _persistentstorecoordinator:nspersistentstorecoordinator? = nil//#pragma mark-application ' s documents Directory//Returns the URL to the application ' s documents Director Y. var applicationdocumentsdirectory:nsurl {Let urls = Nsfilemanager.defaultmanager (). UrlsfordirecTory (. Documentdirectory, Indomains:. Userdomainmask) return urls[urls.endindex-1] as Nsurl} func Savecontext () {var error:nserror? = Ni L Let Managedobjectcontext = Self.managedobjectcontext if managedobjectcontext! = Nil {if manage Dobjectcontext.haschanges &&!managedobjectcontext.save (&error) {//Replace this Implementatio N with code to handle the error appropriately. Abort () causes the application to generate a crash log and terminate. You should don't use the This function in a shipping application, although it could be useful during. println ("Unresolved error \ (error), \ (error.userinfo)") Abort ()}}}
- Modify the Appdelegate.swift. and create an instance of Coredatahelper that is used to manipulate coredata.
applicationWillTerminate(application: UIApplication)Replace all the content after the method with the following code.
var cdh: CoreDataHelper {if !_cdh { _cdh = CoreDataHelper() } return _cdh!}var _cdh: CoreDataHelper? = nil
- Modify the Appdelegate.swift to automatically save the coredata.
The code is as follows:
func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. self.cdh.saveContext()}...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. self.cdh.saveContext()}
Manipulating Model objects
Next we will create a demofamily method to access the CoreData in Appdelegate.swift for manipulating CoreData. This code is executed in func applicationDidBecomeActive(application: UIApplication) , and the result of the operation is viewed from the Log file.
func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. self.demoFamily()}
Demofamily () is implemented as follows, please refer to the note for the code description:
Func demofamily () {var newitemnames = ["Apples", "Milk", "Bread", "Cheese", "sausages", "Butter", "Orange Juice", "cere Al "," Coffee "," Eggs "," tomatoes "," Fish "//Add Families NSLog (" ======== Insert ======== ") for Newitemname in Newitemnames {var newitem:family = nsentitydescription.insertnewobjectforentityforname ("Family", InManagedObject Context:self.cdh.managedObjectContext) as Family newitem.name = Newitemname NSLog ("Inserted New Family for \ (Newitemname)}}//self.cdh.savecontext ()//fetch families NSLog ("======== fetch ========") var error: Nserror? = nil var freq:nsfetchrequest = nsfetchrequest (entityname: "Family")//Set filter Condition Freq.predicate = nspredicate (Form At: "Name CONTAINS ' B '")//Set result collation, set here to reverse by name var Sorter:nssortdescriptor = nssortdescriptor (key: "Name", as Cending:false) freq.sortdescriptors = [Sorter] var result = Self.cdh.managedObjectContext.executeFetchRequest (FReq, Error:&erROR) for Resultitem:anyobject in result {var Familyitem = Resultitem as Family NSLog ("fetched Family F or \ (familyitem.name)}}//delete families NSLog ("======== delete ========") FReq = Nsfetchrequest (Entityn Ame: "Family") result = Self.cdh.managedObjectContext.executeFetchRequest (FReq, error:&error) for resultitem:a Nyobject in result {var Familyitem = Resultitem as Family NSLog ("Deleted Family for \ (familyitem.name)") Self.cdh.managedObjectContext.deleteObject (Familyitem)}//self.cdh.savecontext () NSLog ("======== Check De Lete ======== ") result = Self.cdh.managedObjectContext.executeFetchRequest (FReq, error:&error) if result.isempt y {NSLog ("Deleted All Families")} else{for resultitem:anyobject in result {var family Item = Resultitem as Family NSLog ("fetched Error Family for \ (familyitem.name)")}}}
The
Log output is as follows:
2014-06-07 14:01:53.717 swiftcoredatasimpledemo[18348:1419062] Application windows is expected to a root view contro Ller at the end of application launch2014-06-07 14:01:54.100 swiftcoredatasimpledemo[18348:1419062] ======== Insert ===== = = = 2014-06-07 14:01:54.115 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Apples 2014-06-07 14:01:54.115 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Milk 2014-06-07 14:01:54.115 SWIFTCOREDATASIMPLEDEMO[18348:1419062] Inserted New Family for Bread 2014-06-07 14:01:54.116 swiftcoredatasimpledemo[ 18348:1419062] Inserted New Family for Cheese 2014-06-07 14:01:54.116 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for sausages 2014-06-07 14:01:54.116 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Butter 2014 -06-07 14:01:54.117 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Orange Juice 2014-06-07 14:01:54.117 S WIFTCOREDATASIMPLEDEMO[18348:1419062] Inserted New Family for CeReal 2014-06-07 14:01:54.117 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Coffee 2014-06-07 14:01:54.118 swiftcoredatasimpledemo[18348:1419062] Inserted New Family for Eggs 2014-06-07 14:01:54.118 SWIFTCOREDATASIMPLEDEMO[18348:1419062] Inserted New Family for tomatoes 2014-06-07 14:01:54.118 SWIFTCOREDATASIMPLEDEMO[18348:1419062] Inserted New Family for Fish 2014-06-07 14:01:54.118 swiftcoredatasimpledemo[ 18348:1419062] ======== Fetch ======== 2014-06-07 14:01:54.121 swiftcoredatasimpledemo[18348:1419062] Fetched Family For Butter 2014-06-07 14:01:54.122 swiftcoredatasimpledemo[18348:1419062] fetched Family for Bread 2014-06-07 14:01:54.122 swiftcoredatasimpledemo[18348:1419062] ======== Delete ======== 2014-06-07 14:01:54.123 SWIFTCOREDATASIMPLEDEMO[18348:1419062] Deleted Family for tomatoes 2014-06-07 14:01:54.123 swiftcoredatasimpledemo[ 18348:1419062] Deleted Family for cereal 2014-06-07 14:01:54.123 swiftcoredatasimpledemo[18348:1419062] Deleted Family For OrangE Juice 2014-06-07 14:01:54.123 swiftcoredatasimpledemo[18348:1419062] Deleted Family for Eggs 2014-06-07 14:01:54.124 Sw IFTCOREDATASIMPLEDEMO[18348:1419062] Deleted Family for Milk 2014-06-07 14:01:54.124 swiftcoredatasimpledemo[ 18348:1419062] Deleted Family for Butter 2014-06-07 14:01:54.124 swiftcoredatasimpledemo[18348:1419062] Deleted Family For sausages 2014-06-07 14:01:54.125 swiftcoredatasimpledemo[18348:1419062] Deleted Family for Cheese 2014-06-07 14:01:54.125 swiftcoredatasimpledemo[18348:1419062] Deleted Family for Apples 2014-06-07 14:01:54.125 SWIFTCOREDATASIMPLEDEMO[18348:1419062] Deleted Family for Bread 2014-06-07 14:01:54.125 swiftcoredatasimpledemo[ 18348:1419062] Deleted Family for Fish 2014-06-07 14:01:54.126 swiftcoredatasimpledemo[18348:1419062] Deleted Family for Coffee 2014-06-07 14:01:54.126 swiftcoredatasimpledemo[18348:1419062] ======== Check Delete ======== 2014-06-07 14:01:54.127 swiftcoredatasimpledemo[18348:1419062] Deleted all Familiesprogram ended with Exit Code:9
Member.swift code that does not work
Refer to Swift documentation, attempt to create Member.swift, compile pass, run test failed. Due to the limited documentation, it is impossible to further determine the cause. Recorded here, for everyone to discuss.
The Swift documentation is described below, implementing Core Data Managed Object subclasses
Implementing Core Data Managed Object SubclassesCore Data provides the underlying storage and implementation of properties in subclasses of the NSManagedObject class. Add the @NSManaged attribute before each property definition in your managed object subclass that corresponds to an attribute or relationship in your Core Data model. Like the @dynamic attribute in Objective-C, the @NSManaged attribute informs the Swift compiler that the storage and implementation of a property will be provided at runtime. However, unlike @dynamic, the @NSManaged attribute is available only
According to the documentation member.swift the following:
import CoreDataclass Member: NSManagedObject { @NSManaged var name: String @NSManaged var sex: String @NSManaged var birthday: NSDate}
Comment out the Member.h line in Swiftcoredatasimpledemo-bridging-header.h:
#import "Family.h"// #import "Member.h"
After running, compile successfully, but run error flash, error interface is as follows.
Code address
https://github.com/iascchen/SwiftCoreDataSimpleDemo/
Finish the call.
Author:iascchen (at) gmail (dot) com
Date:2014-6-7
Sina Weibo: @ Ask the sky drum