Simple Introduction
This article documents some of the basics of using Swift to manipulate coredata in IOS, because the lack of documentation is essentially the result of self-experimentation. Mistakes 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 Select the language for Swift. and tick the use Core Data.
- Select the folder where the item is stored
- New projects that you create, such as what you see
Change Core Data Model
- Select the Swiftcoredatasimpledemo.xcdatamodeld file, which is still empty at the moment.
- Create two Entity. Named Family and Member, respectively.
- Before generating the model file, we were able to create a Group named models that holds the generated model files.
- After you select an Entity for the Swiftcoredatasimpledemo.xcdatamodeld file, you can find the Create Nsmanagedobject subclass in the Editor menu, select the project, and start creating the model file.
- Trailing wizard. After the model is created, you can select all of 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.
After the build is complete, you see the new model file in Project.
At this point, the swiftcoredatasimpledemo-bridging-header.h is still empty, and we need to add a header file that we need to be interviewed by Swift. The results for example are as seen in:
#import "Family.h"#import "Member.h"
Change Appdelegate
Similar to the new OBJC App. The new project adds the code that operates coredata to the Appdelegate.swift file. In order to make the code more concise and clear. We will extract this part of the code. Move to the Coredatahelper.swift.
- Open the original appdelegate.swift. In the latter part of the program, you can see the code associated with the Operation CoreData. For example, as seen in.
- The code in Appdelegate.swift
func saveContext ()
and later is selected. Transferred to the Coredatahelper.swift file. And make minor adjustments to it, the use of the project name of the Commission constant, placed in the front of the coredatahelper, so that the future assumes the need to use Coredatahelper in the history project, it is very convenient.
After the completion of the Coredatahelper.swift code such as the following:
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 an error here include: * The persistent store isn't 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 the their frequency by: * Simply Deleting the existing Store:NSFileManager.defaultManager (). Removeitematurl (Storeurl, Error:nil) * Performing automatic lightweight migration by passing the following dictionary as the options parameter: [Nsmig Ratepersistentstoresautomaticallyoption:true, nsinfermappingmodelautomaticallyoption:true} Lightweight Migrat Ion 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 ()}}}
applicationWillTerminate(application: UIApplication)
Replace all content after the method with the following code.
var cdh: CoreDataHelper {if !_cdh { _cdh = CoreDataHelper() } return _cdh!}var _cdh: CoreDataHelper?
= nil
- Change the Appdelegate.swift. Save CoreData on your own initiative.
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'll create a demofamily method for CoreData in Appdelegate.swift to manipulate CoreData. This code is run 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()}
A detailed implementation of demofamily () such as the following, code description please refer to the gaze:
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", Ascending: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 the Swift documentation, attempt to create Member.swift, compile pass, and perform a test failure. Due to the limited documentation, it is impossible to further determine the cause. Recorded here, for everyone to discuss.
Instructions for Swift documentation such as the following, 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
Write member.swift based on documentation such as the following:
import CoreDataclass Member: NSManagedObject { @NSManaged var name: String @NSManaged var sex: String @NSManaged var birthday: NSDate}
To stare at the Member.h line in Swiftcoredatasimpledemo-bridging-header.h:
#import "Family.h"// #import "Member.h"
After execution, the compilation succeeds, but the error is flashed, and the 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
Step by Step does IOS Swift coredata simple Demo