SobjectiveRecord is CoreData Library for iOS, Written in Swift
Switch branches/tags
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
SobjectiveRecord
SobjectiveRecordDemo
.gitignore
LICENSE
README.md
SobjectiveRecord.podspec

README.md

SobjectiveRecord

SobjectiveRecord version SobjectiveRecord platform SobjectiveRecord license Join the chat at https://gitter.im/hmhv/SobjectiveRecord

SobjectiveRecord is Swift version of HobjectiveRecord. with Xcode 6.3

HobjectiveRecord is inspired by ObjectiveRecord and customized for background NSManagedObjectContext.

Before you use, i recommend you read these articles

Usage

  1. copy all files in folder SobjectiveRecord to your project.
    or Install with CocoaPods pod 'SobjectiveRecord'

You should use CocoaPods version 0.36 for Swift
for details read Pod Authors Guide to CocoaPods Frameworks

Initialize

setup your store.

import SobjectiveRecord // when using CocoaPods

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    
    NSPersistentStoreCoordinator.setupDefaultStore()

	// your code here
	
    return true
}

Basic

your entities must have prefix (like projectName.entityName)

entity_prefix.png

you can make your model's typealias for convenience

// User, Tweet are NSManagedObject's subclass
typealias Users = SobjectiveRecord<User>
typealias Tweets = SobjectiveRecord<Tweet>

// so, it's same
var user = SobjectiveRecord<User>.create()
var user = Users.create()

use performBlock

NSManagedObjectContext.defaultContext.performBlock {
    // your code here
}

var moc = NSManagedObjectContext.defaultContext.createChildContext()
moc.performBlock {
    // your code here
}

Create / Save / Delete

NSManagedObjectContext.defaultContext.performBlock {
    var t = Tweets.create()
    t.text = "I am here"
    t.save()
    
    t = Tweets.create(attributes: ["text" : "hello!!", "lang" : "en"])
    t.delete()
}

NSManagedObjectContext.defaultContext.performBlock {
    Tweets.deleteAll()
    NSManagedObjectContext.defaultContext.save()
}

Finders

NSManagedObjectContext.defaultContext.performBlock {
    var tweets = Tweets.all()
    
    var tweetsInEnglish = Tweets.find(condition: "lang == 'en'")
    
    var hmhv = Users.first(condition: "screenName == 'hmhv'")
    
    var englishMen = Users.find(condition: ["lang" : "en", "timeZone" : "London"])
    
    var predicate = NSPredicate(format: "friendsCount > 100")
    var manyFriendsUsers = Users.find(condition: predicate)
}

Order and Limit

NSManagedObjectContext.defaultContext.performBlock {
    var sortedUsers = Users.all(order: "name")
    
    var allUsers = Users.all(order: "screenName ASC, name DESC")
    // or
    var allUsers2 = Users.all(order: "screenName A, name D")
    // or
    var allUsers3 = Users.all(order: "screenName, name d")
    
    var manyFriendsUsers = Users.find(condition: "friendsCount > 100", order: "screenName DESC")
    
    var fiveEnglishUsers = Users.find(condition: "lang == 'en'", order: "screenName ASC", fetchLimit: 5)
}

Aggregation

NSManagedObjectContext.defaultContext.performBlock {
    var allUserCount = Users.count()
    
    var englishUserCount = Users.count(condition: "lang == 'en'")
}

BatchUpdate

NSManagedObjectContext.defaultContext.performBlock {
    
    Users.batchUpdate(condition: "friendsCount > 10", propertiesToUpdate: ["friendsCount": 0])

    // update all entities
    Users.batchUpdate(propertiesToUpdate: ["friendsCount": 100])
}

NSFetchedResultsController

NSManagedObjectContext.defaultContext.performBlock {
    var frc = Users.createFetchedResultsController(order: "name")
    frc.delegate = self
    
    var error: NSError? = nil
    if frc.performFetch(&error) {
        self.reloadData()
    }
}

Custom ManagedObjectContext

var childContext = NSManagedObjectContext.defaultContext.createChildContext()

childContext.performBlock {
    var john = Users.create(context: childContext)
    john.name = "John"
    john.save()
    
    var savedJohn = Users.first(condition: "name == 'John'", context: childContext)
    
    var manyFriendsUsers = Users.find(condition: "friendsCount > 100", order: "screenName DESC", context: childContext)
    
    var allUsers = Users.all(context: childContext)
}

Custom CoreData model or .sqlite database

If you've added the Core Data manually, you can change the custom model and database name.

var modelURL = NSURL.defaultModelURL(modelName: "model_name")
NSPersistentStoreCoordinator.setupDefaultStore(modelURL: modelURL)

// or
var storeURL = NSURL.defaultStoreURL(fileName: "file_name.sqlite")
NSPersistentStoreCoordinator.setupDefaultStore(storeURL: storeURL)

Mapping

The most of the time, your JSON web service returns keys like first_name, last_name, etc.
Your Swift implementation has camelCased properties - firstName, lastName.

camel case is supported automatically - you don't have to do anything! Otherwise, if you have more complex mapping, here's how you do it:

!! Date, Transformable Types and Relationships are not supported !!

// just override +mappings in your NSManagedObject subclass
extension User
{
    override class var mappings: [String: String]? {
        return ["description" : "userDescription"]
    }
}
// first_name => firstName is automatically handled

Testing

SobjectiveRecord supports CoreData's in-memory store. In any place, before your tests start running, it's enough to call

NSPersistentStoreCoordinator.setupDefaultStore(useInMemoryStore: true)

License

SobjectiveRecord is available under the MIT license. See the LICENSE file for more information.