How to use Magical Record in Swift
Magical Record(Objective-C)
Magical Record is Ruby like operation library of CoreData.
It is so useful, but it’s Objective-C.
To use it from Swift, we need more steps
Steps
Bridge Header
Make new BridgeHeader to call Objective-C from Swift.
Create header named YourApplication-Bridging-Header.h
YourApplication is your application name
#ifndef YourApplication_YourApplication_Bridging_Header_h #define YourApplication_YourApplication_Bridging_Header_h #define MR_SHORTHAND #import "CoreData+MagicalRecord.h" #endif
Add “CoreData+MagicalRecord.h”
And set this header as bridge header in Swift Compiler setting(Build Settings)
You can find Objective-C Bridging Header using search(search by objective-c bri).
Model
Model file is same as general Objective-C data file(xcdatamodeld.
Let’s make NSManageObject by XCode.
This is an example data structure
Flashcardpack uuid String name String
This is code
@objc(Flashcardpack) // Important! class Flashcardpack: NSManagedObject { @NSManaged var uuid: String @NSManaged var name: String class func create(uuid: NSString, name: NSString) { var res = Flashcardpack.MR_createEntity() as Flashcardpack res.uuid = uuid res.name = name // Save NSManagedObjectContext.MR_defaultContext().MR_saveToPersistentStoreAndWait() return res; } }
Very simple, isn’t it? The key is to add @objc() …