Easy way to operate for Core Data.
The library is inspired by the active record pattern which is a kind of design pattern to operate database easily.
- Xcode 6.3
- iOS7+ Mac OS X 10.10
- Add the following to your Cartfile:
github "kaneshin/ActiveRecord" ~> 0.1
- Run
carthage update
- Add ActiveRecord as an embedded framework.
- Clone
ActiveRecord-swift
as a git submodule. - Add
ActiveRecord.xcodeproj
file into your Xcode project. - Link
ActiveRecord.framework
product for your target. - Embed
ActiveRecord.framework
ActiveRecord
needs Context
which is contained NSManagedObjectContext
for reading/writing on each threads.
So, you define the application context at first like below:
/**
Application Context, which is inherited ARContext.
It's easier to use than self-defined context.
*/
class AppContext: ARContext {
override init() {
super.init()
self.persistentStoreCoordinator = self.lazyPersistentStoreCoordinator
}
private lazy var lazyPersistentStoreCoordinator: NSPersistentStoreCoordinator? = {
if let managedObjectModel = self.managedObjectModel {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
var error: NSError? = nil
if let url = self.storeURL {
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
}
}
return coordinator
}
return nil;
}()
}
(Please show AppContext.swift in example project.)
And then, setup it into the ActiveRecord
in AppDelegate
.
import UIKit
import ActiveRecord
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
override class func initialize() {
ActiveRecord.setup(context: AppContext())
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
return true
}
}
You can handle NSManagedObject
like active record.
// Create
var event = Event.create(entityName: "Event") as? Event
event.title = "eat"
event.timeStamp = NSDate()
event.save()
// Read
var events = Event.find(entityName: "Event")
// Delete
events?.first?.delete()
- [ ]More ActiveRecord:
let session = ActiveRecord.Session()
var events = session.where("id < ?", userId).limit(10, 20).find("Event")
- Hiroshi Kimura [email protected]
- Kenji Tayama