Coder Social home page Coder Social logo

sugarrecord's Introduction

SugarRecord

Twitter: @carambalabs CocoaPods Compatible Language: Swift Language: Swift Build Status Carthage Compatible

What is SugarRecord?

SugarRecord is a persistence wrapper designed to make working with persistence solutions like CoreData in a much easier way. Thanks to SugarRecord you'll be able to use CoreData with just a few lines of code: Just choose your stack and start playing with your data.

The library is maintained by @carambalabs. You can reach me at [email protected] for help or whatever you need to commend about the library.

paypal

Features

  • Swift 3.0 compatible (Xcode 8.0).
  • Protocols based design.
  • For beginners and advanced users
  • Fully customizable. Build your own stack!
  • Friendly syntax (fluent)
  • Away from Singleton patterns! No shared states ๐ŸŽ‰
  • Compatible with OSX/iOS/watchOS/tvOS
  • Fully tested (thanks Nimble and Quick)
  • Actively supported

Setup

  1. Install CocoaPods. You can do it with gem install cocoapods
  2. Edit your Podfile file and add the following line pod 'SugarRecord'
  3. Update your pods with the command pod install
  4. Open the project from the generated workspace (.xcworkspace file).

Note: You can also test the last commits by specifying it directly in the Podfile line

Available specs Choose the right one depending ton the configuration you need for you app.

pod "SugarRecord/CoreData"
pod "SugarRecord/CoreData+iCloud"
  1. Install Carthage. You can do it with brew install carthage.
  2. Edit your Cartfile file and add the following line `github "carambalabs/sugarrecord".
  3. Execute carthage update
  4. Add the frameworks to your project as explained on the Carthage repository.

Reference

You can check generated SugarRecord documentation here generated automatically with CocoaDocs

How to use

Creating your Storage

A storage represents your database. The first step to start using SugarRecord is initializing the storage. SugarRecord provides a default storages, CoreDataDefaultStorage.

// Initializing CoreDataDefaultStorage
func coreDataStorage() -> CoreDataDefaultStorage {
    let store = CoreDataStore.named("db")
    let bundle = Bundle(for: self.classForCoder)
    let model = CoreDataObjectModel.merged([bundle])
    let defaultStorage = try! CoreDataDefaultStorage(store: store, model: model)
    return defaultStorage
}
Creating an iCloud Storage

SugarRecord supports the integration of CoreData with iCloud. It's very easy to setup since it's implemented in its own storage that you can use from your app, CoreDataiCloudStorage:

// Initializes the CoreDataiCloudStorage
func icloudStorage() -> CoreDataiCloudStorage {
    let bundle = Bundle(for: self.classForCoder)
    let model = CoreDataObjectModel.merged([bundle])
    let icloudConfig = CoreDataiCloudConfig(ubiquitousContentName: "MyDb", ubiquitousContentURL: "Path/", ubiquitousContainerIdentifier: "com.company.MyApp.anothercontainer")
    let icloudStorage = try! CoreDataiCloudStorage(model: model, iCloud: icloudConfig)
    return icloudStorage
}

Contexts

Storages offer multiple kind of contexts that are the entry points to the database. For curious developers, in case of CoreData a context is a wrapper around NSManagedObjectContext. The available contexts are:

  • MainContext: Use it for main thread operations, for example fetches whose data will be presented in the UI.
  • SaveContext: Use this context for background operations. The context is initialized when the storage instance is created. That context is used for storage operations.
  • MemoryContext: Use this context when you want to do some tests and you don't want your changes to be persisted.

Fetching data

let pedros: [Person] = try! db.fetch(FetchRequest<Person>().filtered(with: "name", equalTo: "Pedro"))
let tasks: [Task] = try! db.fetch(FetchRequest<Task>())
let citiesByName: [City] = try! db.fetch(FetchRequest<City>().sorted(with: "name", ascending: true))
let predicate: NSPredicate = NSPredicate(format: "id == %@", "AAAA")
let john: User? = try! db.fetch(FetchRequest<User>().filtered(with: predicate)).first

Remove/Insert/Update operations

Although Contexts offer insertion and deletion methods that you can use it directly SugarRecords aims at using the operation method method provided by the storage for operations that imply modifications of the database models:

  • Context: You can use it for fetching, inserting, deleting. Whatever you need to do with your data.
  • Save: All the changes you apply to that context are in a memory state unless you call the save() method. That method will persist the changes to your store and propagate them across all the available contexts.
do {
  db.operation { (context, save) throws in
    // Do your operations here
    try save()
  }
} catch {
  // There was an error in the operation
}
New model

You can use the context new() method to initialize a model without inserting it in the context:

do {
  db.operation { (context, save) throws in
    let newTask: Track = try context.new()
    newTask.name = "Make CoreData easier!"
    try context.insert(newTask)
    try save()
  }
} catch {
  // There was an error in the operation
}

In order to insert the model into the context you use the insert() method.

Creating a model

You can use the create() for initializing and inserting in the context in the same operation:

do {
  db.operation { (context, save) throws -> Void in
    let newTask: Track = try! context.create()
    newTask.name = "Make CoreData easier!"
    save()
  }
}
catch {
  // There was an error in the operation
}
Delete a model

In a similar way you can use the remove() method from the context passing the objects you want to remove from the database:

do {
  db.operation { (context, save) throws in
    let john: User? = try context.request(User.self).filteredWith("id", equalTo: "1234").fetch().first
    if let john = john {
      try context.remove([john])
      try save()
    }
  }
} catch {
  // There was an error in the operation
}

> This is the first approach of SugarRecord for the interface. We'll improve it with the feedback you can report and according to the use of the framework. Do not hesitate to reach us with your proposals. Everything that has to be with making the use of CoreData easier, funnier, and enjoyable is welcome! ๐ŸŽ‰

RequestObservable

SugarRecord provides a component, RequestObservable that allows observing changes in the DataBase. It uses NSFetchedResultsController under the hood.

Observing

class Presenter {
  var observable: RequestObservable<Track>!

  func setup() {
      let request: FetchRequest<Track> = FetchRequest<Track>().filtered(with: "artist", equalTo: "pedro")
      self.observable = storage.instance.observable(request)
      self.observable.observe { changes in
        case .Initial(let objects):
          print("\(objects.count) objects in the database")
        case .Update(let deletions, let insertions, let modifications):
          print("\(deletions.count) deleted | \(insertions.count) inserted | \(modifications.count) modified")
        case .Error(let error):
          print("Something went wrong")
      }
  }
}

Retain: RequestObservable must be retained during the observation lifecycle. When the RequestObservable instance gets released from memory it stops observing changes from your storage.

NOTE: This was renamed from Observable -> RequestObservable so we are no longer stomping on the RxSwift Observable namespace.

โš ๏ธ RequestObservable is only available for CoreData + OSX since MacOS 10.12

Resources

Contributors

glebosushichopfoxlingZevEisenbergkonyu

yuuki1224YTN01gitter-badgersergigraciaadityatrivedi

Adlai-Hollerakshaynhegdegoingreenstartupthekidctotheameron

davidahouseA8-MokeArasthelLuizZakliterator

madeinqckoliskodukemikerafalwojcikthad

chrispixReadmeCriticavielgrdougangrangej

fjbelchidcvzpepibumur

About

This project is funded and maintained by Caramba. We ๐Ÿ’› open source software!

Check out our other open source projects, read our blog or say ๐Ÿ‘‹ on twitter @carambalabs.

Contribute

Contributions are welcome ๐Ÿค˜ We encourage developers like you to help us improve the projects we've shared with the community. Please see the Contributing Guide and the Code of Conduct.

License

The MIT License (MIT)

Copyright (c) 2017 Caramba

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

sugarrecord's People

Contributors

adityatrivedi avatar adlai-holler avatar akshaynhegde avatar avielg avatar beecity avatar chrispix avatar davidahouse avatar dukemike avatar fjbelchi avatar foxling avatar gitter-badger avatar goingreen avatar grangej avatar jmartinesp avatar kolisko avatar konyu avatar literator avatar luizzak avatar madeinqc avatar omerfarukyilmaz avatar rafalwojcik avatar rdougan avatar readmecritic avatar sergigracia avatar sushichop avatar thad avatar thebarndog avatar ytn01 avatar yuuki1224 avatar zeveisenberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sugarrecord's Issues

New stack structures

Once refactored the library with the stacks support it would be great to have the following stack structures, each of them with its own tests:

  • DefaultCoreData + iCloud
  • DefaultCoreData + RestKit

Import collection into Core Data

In addition of saving and creating methods, add import methods for the use cases which we have a huge collection of data to import into Core Data.

Why doesn't this SugarRecord.operation save?

I am doing a sync of my database.
func syncCategories(){

    var fullStringURL = self.baseStringURL + "/Category.json"
    let URL = NSURL(string:fullStringURL)!
    defaults.objectForKey("lastCategoryUpdate")
    let dateString = defaults.objectForKey("lastCategoryUpdate")! as String
    let parameters:[String:AnyObject] = ["lastmoddate":dateString]


    Alamofire.request(.GET, URL, parameters: parameters)
        .responseJSON { (req, res, json, error) in
            if(error != nil) {
                NSLog("Error: \(error)")
                println(req)
                println(res)
            }
            else {
                var json = JSON(json!)

                SugarRecord.operation(inBackground: true, stackType: SugarRecordStackType.SugarRecordStackTypeCoreData, closure: { (context) -> () in
                    context.beginWriting()

                    for (index: String, subJson: JSON) in json {
                        if let extId:NSNumber = subJson["id"].number{

                            var category: Categorization? = Categorization.by("extID", equalTo: "\(extId)").find()?.first as Categorization?

                            if(category == nil){
                                category = Categorization.create(inContext: context) as? Categorization
                                context.insertObject(category!)
                            }

                            category!.extID = extId

                            if let userName = subJson["name"].string{
                                category!.name = userName
                            }
                            if let mainImage = subJson["mainImage"].string{
                                category!.mainImageURL = mainImage
                            }
                            if let thumbnailImage = subJson["thumbnailImage"].string{
                                category!.thumbnailURL = thumbnailImage
                            }


                        }else{
                            //skip
                        }
                    }
                    context.endWriting()
                })
            }
    }

}

Does SugarRecordFinder support fetchOffset?

I'm using SugarRecord but have an issue: i can't execute page request.

fetchRequest.fetchOffset = page * size;
fetchRequest.fetchLimit = size;

I know SugarRecordFinder have an firsts() function, but can't set offset.
And, SugarRecord.operations give me a SugarRecordContext, so i can't use NSManagedObjectContext direct.

Add an example project

Idea

  • TableView with different options (CoreData, CoreData+RestKit, CoreData+iCloud)
  • Each of them opens an TableViewController with a representative example
  • Each of them with a TableView and a "+" button on the top right corner.
  • Every time you press that button it creates a database object with a random string and the current date.

Todo

  • Update README/Wiki with information about the example
  • Add CoreData+RestKit
  • Add Realm

Stack Interface

Offer a protocol and implementations to let a consumer implement its own custom stack.

Swift ManagedObjects are not working yet? (creating obj-c subclass fixes the issue)

Hi there!
First, thanks for this project, it looks awesome! I'm just starting to use it but the potential is very great :)

Ok, I started using it on a new project so I created my first NSManagedObject subclass as a Swift file.

I encountered an issue with this line of code in NSManagedObject+Stack.swift inside class func entityDescription(inContext context: NSManagedObjectContext?) -> (NSEntityDescription) method:

return NSEntityDescription.entityForName(entityName, inManagedObjectContext: context!)!

This returns EXC_BAD_INSTRUCTION and the debugger logs:
fatal error: unexpectedly found nil while unwrapping an Optional value.

To fix this I thought about removing the NSManagedObject Swift file and rebuild it in Objective-C (and add it to the "APP-Bridging-Header.h"). Then it all works like a charm.

For me is not a big deal because if I want to extend it in Swift I use and it works:

extension managedClassName {

}

...I will never overwrite a subclass like this anyway

I say this because I haven't found anything about this on the README file and it may help other people that are stuck on the same issue. This fixes the issue, but a lot of people may be creating Swift subclasses (All in in Swift!!!) and hitting this wall.

Thanks again for this fantastic project ๐Ÿ‘

Extra Argument in Call to Query

Thanks for the hard work - great library!!!

Just running into an issue with a query - in the example

users: [User]? = User("age", equalTo: "10").sorted(by:"name", ascending: true).find()? 

We get an error of "Extra Argument in Call" for the initial method call...

User("age", equalTo: "10")

Should we be extending our objects from something else besides NSManagedObject

thanks for your help

Migrations support

Think about how to bring migrations to the Library supporting both Realm and CoreData with the SugarRecordAbstraction

Rename savingBlock

In swift we don't have blocks anymore, we could give a more appropriate name for this

Cocoapods support

Quick podspec

Pod::Spec.new do |s|
  s.name         = "Quick"
  s.version      = "0.2.0"
  s.summary      = "The Swift (and Objective-C) testing framework."

  s.description  = <<-DESC
                   Quick is a behavior-driven development framework for Swift and Objective-C. Inspired by RSpec, Specta, and Ginkgo.
                   DESC

  s.homepage     = "https://github.com/Quick/Quick"
  s.license      = { :type => "Apache 2.0", :file => "LICENSE" }

  s.author       = "Quick Contributors"
  s.ios.deployment_target = "8.0"
  s.osx.deployment_target = "10.10"

  s.source       = { :git => "https://github.com/Quick/Quick.git", :tag => "v0.2.0" }
  s.source_files  = "Quick", "Quick/**/*.{swift,h,m}"

  s.framework = "XCTest"
end

How to Install Quick using Beta CocoaPods

If you would like to use Quick with CocoaPods today, you will need to use
rubygem's Bundler to use the swift branch of CocoaPods. This
can be done by including a Gemfile that looks like this:

source 'https://rubygems.org'

gem 'cocoapods', :git => 'https://github.com/CocoaPods/CocoaPods.git', :branch => 'swift'
gem 'cocoapods-core', :git => 'https://github.com/CocoaPods/Core.git', :branch => 'swift'
gem 'xcodeproj',  :git => "https://github.com/CocoaPods/Xcodeproj.git", :branch => 'ext_build_settings'

Then run bundle install to start using Swift CocoaPods for just this project.
Then in your Podfile, add the following to your test target.

  pod 'Quick', :git => "https://github.com/Quick/Quick", :head

Finally, run bundle exec pod install. The bundle exec ensures you're using
the Swift CocoaPods version from your Gemfile.

  • Try to generate a CocoaPods template and see the naming of the umbrella file (bridging for the pod)

Errors after sugarrecord submodule update

I pulled sugarrecord submodule HEAD and changed the setup (added core and Realm folders directly to project) and now I get two new errors:

for this code:
var dbCards: [Card]? = Card.by("cloudUUID", equalTo: ""(cardUUID!)"").find() as [Card]?
I get "extra argument equalTo: in call"

and then for
card.beginWriting()
I get "Ambiguous use of beginWriting"

Card of course is a RLMObject

I don't seem to have any other Realm or SugarRecord errors

Compatibility issue with MOGenerator

you have a method entityName() in your NSManagedObject extension. MOGenerator adds its own.

I would suggest you rename yours so they will work easily together and MOGenerator has been around for years.

Tests order

Is there any way to control the tests order?
I have a class that has an static property, and in each suite of tests what I do is to set that static property to be tested in the suite tests. However before one of the suites has finished, the other is started and it changes that static property and the pending tests start failing. Is there any way to control that?

Thanks

Find all records works incorrectly for me

Hello guys,
I'd liked to write on Stackoverflow but I don't have enough reputations to use SugarRecord :/.
I really like SugarRecord! I use it on my personal project with success except for find records correctly of my table "Setting". In fact I write this code:

let settings = Setting.find(.all, inContext: nil, filteredBy: nil, sortedBy: nil)

And it retrieve correctly my 5 records. But if I add subsequently a record and redo "Setting.find(.all..." it retrieve 11 record instead of 6. Why? :(

Review closures retaining

We're using closures in Swift but we have to be careful with them because we could have the same retaining cycles that we had in case of blocks in Objective-C. Review where we are using them and if we are passing the variables from outside with the proper referencing type.

Depends on this issue (to avoid possible conflicts in naming): #11

Update Realm submodule

Hi there, any plans to update the Realm submodule? It's got some new features that i'd like to use e.g. Optional properties and not having to make model object a direct subclass of RLMObject

can pass compile

I can pass compile at xcode 6.1.1(6A2006)

at last of iCloudCDStack.swift line 267, lastPathComponent is a Optional Value, should add "!" ?

self!.databasePath = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudDataDirectoryName).stringByAppendingPathComponent(self!.databasePath!.lastPathComponent))

Add option to cancel write transaction

Realm has a feature to cancel a write operation. We should support it too in SugarRecord. This way if the user inserted the object in the SugarRecordContext and he/she ends up cancelling it, there's no need to commit and then delete. Just cancel the operation

The RSS App demand

Hi! @pepibumur
Thank you for your open source.

If i need to update a model few fields, then how to do?

The RSS App, now update some articles to read.

So the question comes, we have one million data needs to be mark read, that do?

Jack

Crash at start of app in iOS 7

Hello,
in iOS 8 SugarRecord works perfectly but when I run my app on iOS 7 Simulator it crash with:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSManagedObjectContext setName:]: unrecognized selector sent to instance 0x7ff03951d310'


In applicationDidFinishLaunchingWithOptions I have this code:

    let stack: DefaultCDStack = DefaultCDStack(databaseName: "Database.sqlite", automigrating: true)
    SugarRecord.addStack(stack)
    SugarRecordLogger.currentLevel = SugarRecordLogger.logLevelVerbose

Use of generics for SugarRecord finder

Why?

Because that's gonna avoid the casting on the database fetches. Generic methods are going to know which objects have to be returned and they are not going to return something like [AnyObject] like they did until now.

How to manually call the save method?

I found that when i call model.save() or model.endWriting(), they are not save to database.
Sometimes , I want to manually call the save method to save data immediately in database.
like:

[MagicalRecord saveUsingCurrentThreadContextWithBlockAndWait:nil];

unable to install sugarrecord as submodule

I'm trying to setup my project to use sugarrecord as a submodule but i am unable to get the application to compile.

I want to use CoreData and RestKit, and I followed your instructions on the wiki, but it keeps saying builds fails (no error) i'm not sure what i'm doing wrong.

do you have example application that has sugarrecord imported as a submodule?

Bring Sugar syntax on board

One of the most remarkable features of Swift is its sugar syntax and it's time to bring it to SugarRecord too. This issue is opened as a brainStorming to talk about the syntax and how we could refactor our methods.

Syntax

// Operations with contexts
person.save()
person.save(asynchronously)
person.inContext(context).save()
person.inContext(context).save(asynchronously)

// Main examples
Person.by("name", "Pedro").sorting("age", ascending: true).fist() // -> NSFetchRequest
Person.by("name", "Pedro").sorting("age", ascending: true).first(20).find() // -> [NSManagedObject]?
Person.by("name", "Pedro").sorting("age", ascending: true).last().find(context) // -> [NSManagedObject]?
Person.by("name", "Pedro").sorting("age", ascending: true).all().find(context, asynchronously: true) // -> [NSManagedObject]?

// Alternatives around previous idea
Person.by("name", "Pedro").all // -> NSFetchRequest
Person.by("name", "Pedro").first(20) // -> NSFetchRequest
Person.by("name", "Pedro").last(20) // -> NSFetchRequest
Person.by("name", "Pedro").all // -> NSFetchRequest
Person.by("name", "Pedro").first // -> NSFetchRequest

// FetchedResultsController
Person.by("name","Pedro").fetchedResultsController() // -> NSFetchedResultsController

Requirements

Generated framework cannot be used in 7.0

ld: embedded dylibs/frameworks are only supported on iOS 8.0 and later (@rpath/SugarRecord.framework/SugarRecord) for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

iCould support

Which iOS version for iCloud is supported iOS 7, iOS 8 or both. And is there some specific steps to add iCloud support different from just change the CoreDataStack and enable iCloud?

Missing argument for parameter 'inContext' in call

I was using an older version of SugarRecord, but I just updated to the latest revision of the code, and I'm getting these compiler errors.

/SugarRecord/library/CoreData/Base/NSManagedObject+SugarRecord.swift:178:27: Missing argument for parameter 'inContext' in call

/SugarRecord/library/CoreData/Base/NSManagedObject+SugarRecord.swift:275:24: Could not find member 'beginWriting'

/SugarRecord/library/CoreData/Base/NSManagedObject+SugarRecord.swift:286:24: Could not find member 'endWriting'

/SugarRecord/library/CoreData/Base/NSManagedObject+SugarRecord.swift:295:24: Could not find member 'cancelWriting'

Not sure if there was anything I missed.

mergeChangesInMainThread: could not be called and exception raised

Because mergeChangesInMainThread(fromNotification:) is exported to ObjC runtime as mergeChangesInMainThreadFromNotification:, calling the method from NSNotificationCenter is failing.

if mainThread {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("mergeChangesInMainThreadFromNotification:"), name: NSManagedObjectContextDidSaveNotification, object: context)
}

or

@objc(mergeChangesInMainThread:)
func mergeChangesInMainThread(fromNotification notification: NSNotification)

or

func mergeChangesInMainThread(notification: NSNotification)

fixes the issue.

func mergeChanges(fromNotification notification: NSNotification) would be the same.

Generate documentation using Jazzy

It seems that Jazzy has been updated to support the last version of XCode
Use it to generate documentation for SugarRecord and upload the generated doc to
http://sugarrecord.com/docs

Single quote the string predicates on the finder and consider other types

What?

  • Commented here: #87 (comment)
    Just how we have implemented the finder if you want to filter using an string you have to single-quote it which is something most of users forget about.
  • We could split the by() method into:
    by(name: String, stringValue: String)
    by(name: String, intValue: String)

Steps

  • Add methods to the SugarRecordObjectProtocol
  • Add methods to the Finder
  • Test SugarRecord objects methods:
    • Objective-C
    • Realm
  • Teste SugarRecordFinder methods:
    Note: Basically the tests would consist on checking if the predicate has the right format

Refactor by(... method to support Swift Literal Convertible

What?

Instead of having a method like this one:

public class func by(key: String, equalTo value: String) -> SugarRecordFinder

We could have a method like this one

public class func by(key: String, equalTo value: StringLiteralConvertible) -> SugarRecordFinder

Allowing the users to use other types besides Strings. Check if we can apply that in some other places around the app.

Allow working with RLMArray

Regarding the last update notes, http://realm.io/news/realm-cocoa-0.86.0/:

Each subclass is treated as an entirely distinct type containing all of the properties defined on it and all of its parent classes. This means that you can do things like [company.employees objectsWhere:@"name > 25"](querying an object based on a property defined in a parent class), but you cannot use an object of a subclass in a relationship where the parent is expected. That is, the following does not work:

Improvements

  • Querying Improvements and Fixes

Questions to contribute

Hi Pedro,

I have a few questions and suggestions to contribute:

  1. CI : Adding new code or refactoring, I think it's going to be need to have a CI running the unit tests. I've seen you integrated Quick for it :)
    This morning I've tried to integrate Travis-CI into my fork, but I haven't had luck yet, I made the tests pass with xcodebuild:
    xcodebuild test -project SugarRecordDemo/SugarRecord.xcodeproj -scheme SugarRecord -sdk iphonesimulator ONLY_ACTIVE_ARCH=NO but I couldn't with xctool, it seems not supported for xcode6-betas
  2. Yesterday reading the code in one file made difficult to track every component of the library. Do have plans to split the code in files?
  3. Is there a code convention you are following? - I always try to follow the convention I see written in current code.
  4. Do you have plans to create an open source organisation SugarRecord to host the project? in the same way as Quick or MR does. I think it will be more convenient to add developers to contribute.
  5. I was wondering if perhaps would be possible to add more syntactic sugar format, I don't know how yet, maybe here we can have some ideas : https://github.com/supermarin/ObjectiveSugar and also taking the advantages of all swift features.

Cheers

setting default context missing?

Hi!
I am trying to use SugarRecord and got some assertions. I've checked the reason and I think the following function is missing a line:

class func initializeContextsStack(persistentStoreCoordinator: NSPersistentStoreCoordinator) {
        SugarRecordLogger.logLevelInfo.log("Creating contexts stack")
        var rootContext: NSManagedObjectContext = NSManagedObjectContext.newContext(nil, persistentStoreCoordinator: persistentStoreCoordinator)
        NSManagedObjectContext.setRootSavingContext(rootContext)
        var defaultContext: NSManagedObjectContext = NSManagedObjectContext.newContext(rootContext, persistentStoreCoordinator: nil)
}

Isn't there a line

        NSManagedObjectContext.setDefaultContext(defaultContext)

missing?

Extra Argument 'equalTo:' issue

Why won't this compile:

if let extId:NSNumber = subJson["id"].number{

==> error here: let category: Categorization? = Categorization.by("extID", equalTo: extId).find()?.first as Categorization?

FetchedResultsController methods

Create any extension of NSManagedObject to generate automatically a fetchedResultsController with the passed filtering, and sorting data.

Operations examples not working, or insufficient setup instructions

I have a Realm model like this:

import Realm

// IdentityProxy model
class IdentityProxy: RLMObject {
dynamic var name = ""
dynamic var title = ""
dynamic var imageUrl = ""
dynamic var cloudUUID = ""
dynamic var changeDate = NSDate(timeIntervalSince1970: 1)
}

but I can't get the RLMObject SugarRecord operations to work, e.g.:

    let idents: [IdentityProxy]? = IdentityProxy("cloudUUID", equalTo: "someuuid").find() as [IdentityProxy]?

gives the error "Extra argument in call"

none of the other SugarRecord code gives any errors, e.g. SugarRecord.addStack...

I'm successful with pure Realm, like so:

                var idents = IdentityProxy.objectsWhere("cloudUUID = '\(identUUID!)'")

but I can't use that inside SugarRecord.operation without it crashing Realm by being on the wrong thread.

Fix Travis

What?

For any reason Travis is failing. Try to fix it and leave it passing for future PR proposals

Project or target for CocoaTouch framework

Awesome work guys! Thank you for this. Any specific reason why you didn't include a CocoaTouch Framework project or a target for this? Similar libraries (Alamofire i.e.) are including CocoaTouch Framework projects so one could just include that project and add link+copy the framework. I think that's a little bit nicer than including the sources directly. I've done something similar here, but I'm not submitting a PR because I think this should be done by someone of the core team, you know just to get the organization information right.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.