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


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

#import "CoreData+MagicalRecord.h"

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).
bridge header


Model file is same as general Objective-C data file(xcdatamodeld.
Let’s make NSManageObject by XCode.
This is an example data structure

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 = name
        // Save
        return res;

Very simple, isn’t it? The key is to add @objc() …