Step by Step Do iOS Swift CoreData Simple Demo (deprecated)#
This is a simple demo of access iOS core data in swift.
Tested in Xcode7.2.1 and Swift 2 (2016-02-14)
Support multi-thread Contexts
Florian Kugler gaved some advices for core data performance, Concurrent Core Data Stacks – Performance Shootout and Backstage with Nested Managed Object Contexts.
I changed the implements to support this best practice. We should better write data in private background context, and read data from main queue context.
Step by Step
Common Steps
- Create an Empty Application, and select in Swift language and use CoreData.
- Modify generated code about persistentStoreCoordinator in AppDelegate.swift to CoreDataStore.
- Modify generated code about NSManagedObjectContext in AppDelegate.swift to CoreDataHelper.
- Adjust AppDelegate.swift to use CoreDataStore and CoreDataHelper.
Data Models
- Create some entity in
SwiftCoreDataSimpleDemo.xcdatamodeld
, such as Family and Member.
- Add “members” attribute of Family, set relationship with Member/family, and “to Many”, select delete rule as “Cascaded”.
- Add “family” attribute of Member, set relationship with Family/members, and “to One”, unselect the checkbox of “Options”.
- Generate the NSManagedObject files in Swift.
- You have to add sentences like
@objc(ClassName)
to Member.swift and Family.swift manually. (Thanks for joshhinman’s contributions.)
such as:
import CoreData
@objc(Member)
class Member: NSManagedObject {
@NSManaged var name: String
@NSManaged var sex: String
@NSManaged var birthday: NSDate
}
About Demo Code
- Add func demoFamily() to AppDelegate.swift, this is a demo of basic CoreData CRUD.
- Add func demoMember() to AppDelegate.swift, this is a demo of relationship, and delete cascaded.
- If you want to use CoreDataHelper in UIViewController, you’d better add a CoreDataHelper instance for each UIViewController. All CoreDataHelper instance share one CoreDataStore defined in AppDelegate.swift.
- Generally, We should better write data in private background context, and read data from main queue context.
- BUT please make sure the context of saved the object is same with which fetched it.
Other
There are a detail documents in Chinese at here.
Or you can read the pictures and the codes. 😃
Author : iascchen(at)gmail(dot)com
Date : 2014-8-28
新浪微博 : @问天鼓