A powerful and elegant Core Data framework for Swift.

Overview

AlecrimCoreData

Version Language: swift Platforms License: MIT Author: Vanderlei Martinelli

A powerful and elegant Core Data framework for Swift.

Usage

Beta version. New docs soon...

Simple do that:

let query = persistentContainer.viewContext.people
    .where { \.city == "Piracicaba" }
    .orderBy { \.name }

for person in query.dropFirst(20).prefix(10) {
    print(person.name, person.address)
}

Or that:

persistentContainer.performBackgroundTask { context in
    let query = context.people
        .filtered(using: \.country == "Brazil" && \.isContributor == true)
        .sorted(by: .descending(\.contributionCount))
        .sorted(by: \.name)

    if let person = query.first() {
        print(person.name, person.email)
    }
}

After that:

import AlecrimCoreData

extension ManagedObjectContext {
    var people: Query { return Query(in: self) }
}

let persistentContainer = PersistentContainer()

And after your have created your matching managed object model in Xcode, of course. ;-)

Contribute

If you have any problems or need more information, please open an issue using the provided GitHub link.

You can also contribute by fixing errors or creating new features. When doing this, please submit your pull requests to this repository as I do not have much time to "hunt" forks for not submitted patches.

  • master - The production branch. Clone or fork this repository for the latest copy.
  • develop - The active development branch. Pull requests should be directed to this branch.

Contact the author

License

AlecrimCoreData is released under an MIT license. See LICENSE for more information.

Comments
  • All ManagedObjectContexts are leaking - won't deinit.

    All ManagedObjectContexts are leaking - won't deinit.

    ManagedObjectContext and all of it's subclasses are creating a retain cycle and never deinit.

    EDIT My original cause (quoted below) for this was wrong. I realized that the observer object is NOT self its the observer created by the NSNotificationCenter.

    There is still an issue here, as my contexts are never calling deinit, but that is not the reason why. I'll continue to try and profile this.

    This causes a memory leak, and also is causing sporadic crashes for me when old, unused contexts try to merge changes from the root context after when a save finished.

    On initialization, the context is creating an observation for NSManagedObjectContextWillSaveNotification on self. Then, it adds self to it's observers array. By adding itself to the array, the context creates a retain cycle for itself. The context will never be deallocated, and removeObserver will never be called.

    opened by AnthonyMDev 19
  • NativePersistentContainer errors with iOS 10

    NativePersistentContainer errors with iOS 10

    Hello, I have installed the new AlecrimCoreData (5.0) and my project target is iOS 9. Every time I try to build the project I get an error in the AlecrimCoreData/NativePersistentContainer file saying: 'NSPersistentContainer' is only available on iOS 10.0 or newer. Am I doing something wrong or how can I get around this? screen shot 2016-10-22 at 1 11 14 pm

    opened by edwardgroberski 17
  • Swift 3.0 Compatibility

    Swift 3.0 Compatibility

    The previous Swift 3 migration branch was outdated and attempting to merge it with develop didn't work out very well. I've gone ahead and re-done the conversion based on the current develop branch.

    This does not include the conversion for ACDGen, only for AlecrimCoreData.

    opened by AnthonyMDev 17
  • Error: `fatal error: unexpectedly found nil while unwrapping an Optional value`

    Error: `fatal error: unexpectedly found nil while unwrapping an Optional value`

    Hi. I searched a lot for this issue however I can't find any solution.

    _The same issue is mentioned in another thread, I have done what was suggested however still I got the same issue._

    In DataContext.swift

    let dataContext = DataContext()
    class DataContext: Context {
        var profile:      Table<Profile>     { return Table<Profile>(context: self) }
    }
    

    In the a view controller in viewDidLoad

     let person = dataContext.profile.createEntity()
     person.email = "[email protected]"
     person.first_name = "a_name"
     let (success, error) = dataContext.save()
     if success {
          let count = dataContext.profile.count()
          println(count)
     }
     else {
           println(error)
     }
    

    Error: fatal error: unexpectedly found nil while unwrapping an Optional value

    screen shot 2015-09-11 at 1 22 45 pm

    I installed module via CocoPods

    opened by houmanka 16
  • Closure Error

    Closure Error

    when attempting this:

    if let person = dataContext.people.first({ $0.identifier == 123 }) {
        println(person.name)
    }
    

    I get the error: Type of expression is ambiguous without more context

    It may be a syntax issue since I'm fairly new to swift.

    not applicable anymore 
    opened by waltermvp 14
  • Save data but crashed at try super.save()

    Save data but crashed at try super.save()

    When I try to save data with Swift2.0. The program broke down at , When I ran again, the data has been saved into the database when fetch them. how to solve that?

      public override func save() throws {
            guard self.hasChanges else { return }
    
            try super.save()   <------------- This point
    
            var error: ErrorType? = nil
            self.rootSavingDataContext.performBlockAndWait {
                self.enableMergeFromRootSavingDataContext = false
                defer { self.enableMergeFromRootSavingDataContext = true }
    
                do {
                    try self.rootSavingDataContext.save()
                }
                catch let innerError {
                    error = innerError
                }
            }
    
            if let error = error {
                throw error
            }
        }
    

    My Code is:

      @IBAction func doCreate(sender: AnyObject) {
    
            let dataContext = DataContext();
            let gang = dataContext.gangs.createEntity();
            gang.nick = randomStringWithLength(5);
    
            gang.nick_py = randomStringWithLength(5);
    
    
            do {
               try dataContext.save()
            }
            catch let error {
               print("data saved error \(error)")
            }
    }
    
    
    
        }
    
    more info needed investigating not applicable anymore 
    opened by gizcloud 13
  • removeObservers crash

    removeObservers crash

    Using swift 2

    import AlecrimCoreData
    
    public class MyContextData {
        public static let sharedInstance = DataContext()
    }
    
    extension DataContext {
        var cards:      Table<Card>     { return Table<Card>(dataContext: self) }
    }
    
    class Card: NSManagedObject {
        @NSManaged var id: String?
    }
    

    Calling the code below

    let card = MyContextData.sharedInstance.users.createEntity()
    

    gives crash on ManagedObjectContext Line 323

        private func removeObservers() {
            let notificationCenter = NSNotificationCenter.defaultCenter()
    
            for observer in self.observers { // This line crashes
                notificationCenter.removeObserver(observer)
            }
        }
    
    more info needed 
    opened by thellimist 11
  • Carthage Support

    Carthage Support

    Hi everyone. It seems there is no support for Carthage yet.

    carthage update --platform iOS *** Cloning AlecrimCoreData *** Checking out AlecrimCoreData at "4.0.3" *** xcodebuild output can be found in /var/folders/jt/skm6ggy95l18tbmfvgwkh7f80000gn/T/carthage-xcodebuild.GZ1FUj.log *** Building scheme "Alamofire iOS" in Alamofire.xcworkspace Dependency "AlecrimCoreData" has no shared framework schemes

    If you believe this to be an error, please file an issue with the maintainers at https://github.com/Alecrim/AlecrimCoreData/issues/new

    Can we do something about it ? Thanks

    third-party issue feature request 
    opened by StevenMasini 9
  • how to init managedObjectModelName

    how to init managedObjectModelName

    kCFBundleNameKey is not what I want, I changed the Bundle name in plist file

    if self.managedObjectModelName == nil { if let infoDictionary = self.mainBundle.infoDictionary { self.managedObjectModelName = infoDictionary[kCFBundleNameKey] as? String } }

    fatal error: unexpectedly found nil while unwrapping an Optional value

    opened by FredJiang 9
  • NSInvalidArgumentException', reason: 'Unacceptable type of value for to-one relationship ... desired type = Towns; given type = Towns

    NSInvalidArgumentException', reason: 'Unacceptable type of value for to-one relationship ... desired type = Towns; given type = Towns

    Hello there,

    So, I'm scratching my head since few hours and I can't understand this.

    So, I have 2 entities in my core data model:

    Towns Restaurant

    I have defined the relationship one to many and inverse. (yep, you've got it, a Town can have multiple restaurants ;))

    I'm using the CoreData Stack to persist elements from CloudKit. In a class that grab content from ClouKit, I create the context:

    let dataContext = DataContext()
    

    Then I have a bunch of functions that call class functions that create if needed the NSManagedObjects

    let town = Towns.createTownsFromCK(record, dataContext: self.dataContext) ...
    let restaurant = Restaurants.createRestaurantFromCK(record, dataContext: self.dataContext) ...
    

    As you can see I transmit the dataContext. So it's the same for Restaurants and Towns. CloudKit restaurant objects are grabbed after Towns have been locally saved.

    do {
         try dataContext.save()
    } catch {
    
    }
    
    let restaurantPredicate = NSPredicate(format: "town == %@", record.recordID)
    let restaurantQuery = CKQuery(recordType: "Restaurants", predicate: restaurantPredicate)
    self.publicDB.addOperation(createQueryOperation(restaurantQuery, cursor: nil, resultblock:fetchedRestaurantsRecord))
    

    When grabbed, I can create restaurants NSManagedObject and add properties, but when I want to link the town, I have this strange error when I set the town:

    if let cktownreference = record["town"] as? CKReference, town = dataContext.towns.filter({ $0.ckid! == cktownreference.recordID.recordName }).first {
            restaurant.town = town
     }
    

    The error (weird one...):

    Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unacceptable type of value for to-one relationship: property = "town"; desired type = Towns; given type = Towns; value = <Towns: 0x7ff9f8d06ff0> (entity: Towns; id: 0xd000000000080000 <x-coredata://0DEF9EB6-F096-41FE-ACDA-E19B06340183/Towns/p2> ; data: {
        ckid = "6665ca0f-af57-4305-8e18-ced7540e6279";
        name = Paris;
        recordChangeTag = ii0l38hp;
        restaurant = "<relationship fault: 0x7ff9fbb56950 'restaurant'>";
    }).'
    

    Here are my Model:

    capture d ecran 2015-12-14 a 19 42 55 capture d ecran 2015-12-14 a 19 42 45

    1000 thanks for your help! Do not hesitate to ask me questions if it's not clear.

    Matthieu

    more info needed not applicable anymore 
    opened by thieu75 8
  • How to handle database version  update?

    How to handle database version update?

    When I add a new field in my CoreData entity,the framework throws an error at this line.

    internal var contextOptions: ContextOptions { return self.stack.contextOptions }

    I want to know how to resolve this issue,because app's table structure often needs to be updated.

    enhancement 
    opened by tounaobun 8
  • Migrating 5.2 to 6.0.1

    Migrating 5.2 to 6.0.1

    Hello, I am trying to migrate our project from version 5.2 to 6.0.1 and I am encountering some problems. Below is current code

    import AlecrimCoreData
    import CoreData
    import CoreLocation
    
    open class AbstractCoordinateCD: NSManagedObject {
    
        @NSManaged open var latitude: CLLocationDegrees
        @NSManaged open var longitude: CLLocationDegrees
    }
    
    // MARK: - AbstractCoordinateCD query attributes
    extension AbstractCoordinateCD {
    
        static let latitude = AlecrimCoreData.Attribute<CLLocationDegrees>("latitude")
        static let longitude = AlecrimCoreData.Attribute<CLLocationDegrees>("longitude")
    }
    
    // MARK: - AttributeProtocol extensions
    extension AlecrimCoreData.AttributeProtocol where Self.ValueType: AbstractCoordinateCD {
    
        var latitude: AlecrimCoreData.Attribute<CLLocationDegrees> { return AlecrimCoreData.Attribute<CLLocationDegrees>("latitude", self) }
        var longitude: AlecrimCoreData.Attribute<CLLocationDegrees> { return AlecrimCoreData.Attribute<CLLocationDegrees>("longitude", self) }
    }
    
    extension AlecrimCoreData.TableProtocol where Self.Element: AbstractCoordinateCD {
    
        func create(_ coordinate: CLLocationCoordinate2D) -> Self.Element {
            let retValue = create()
            retValue.latitude = coordinate.latitude
            retValue.longitude = coordinate.longitude
            return retValue
        }
    }
    
    extension AbstractCoordinateCD {
    
        var coordinate: CLLocationCoordinate2D {
            return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
        }
    }
    

    In version 6.0.1 there is no AlecrimCoreData.Attribute, AlecrimCoreData.AttributeProtocol, AlecrimCoreData.TableProtocol ... maybe I am blind, but I don't find any alternatives in 6.0.1 version. Can somebody help me please?

    opened by JakubLares 1
  • No way to set relationshipKeyPathsForPrefetching

    No way to set relationshipKeyPathsForPrefetching

    I am wanting to include this attribute in a FetchRequest so I can construct a FetchRequestController with it, but since there is no property for it on FetchRequest, nor a constructor that would take an NSFetchRequest to represent the internal state there doesn't seem to be a way to do this using extensions.

    Was thinking something like this syntax would work:

    func include(relationships: String...) -> FetchRequest<Entity>
    

    And in a Query:

    func include(relationships: String...) -> Query<Entity>
    

    Am I missing an avenue to do this external to the framework?

    opened by johnclayton 0
  • 'Query' is ambiguous for type lookup in this context

    'Query' is ambiguous for type lookup in this context

    I am new to Core data. Now i am trying to load scheme from local database but it shows me error.

    This is error in Query method screen shot 2561-11-30 at 10 47 10 am

    This is RecentCalls model is auto generated when we created Entity in our model screen shot 2561-11-30 at 10 47 28 am

    screen shot 2561-11-30 at 10 50 53 am

    opened by SamboVisal 0
  • Cannot init the PersistentContainer

    Cannot init the PersistentContainer

    let persistentContainer = PersistentContainer()

    Thread 1: Fatal error: 'try!' expression unexpectedly raised an error: AlecrimCoreData.PersistentContainerError.invalidManagedObjectModelURL

    cap

    opened by YLKwan 5
  • Two persistent stores

    Two persistent stores

    I am migrating from MagicalRecord where I use two persistent stores. And though I see the CustomPersistentContainer, which apparently I can override, I still cannot figure how to add more than one store. And the difficult thing here is that one is store is always there, but the other store could be added later on (not during the initialization). Is there way to override/extend the framework to achieve that?

    question 
    opened by rzolin 0
Releases(7.0-beta.1)
Owner
null
JSON to Core Data and back. Swift Core Data Sync.

Notice: Sync was supported from it's creation back in 2014 until March 2021 Moving forward I won't be able to support this project since I'm no longer

Nes 2.5k Dec 31, 2022
CloudCore is a framework that manages syncing between iCloud (CloudKit) and Core Data written on native Swift.

CloudCore CloudCore is a framework that manages syncing between iCloud (CloudKit) and Core Data written on native Swift. Features Leveraging NSPersist

deeje cooley 123 Dec 31, 2022
A synchronization framework for Core Data.

Core Data Ensembles Author: Drew McCormack Created: 29th September, 2013 Last Updated: 15th February, 2017 Ensembles 2 is now available for purchase a

Drew McCormack 1.6k Dec 6, 2022
Unleashing the real power of Core Data with the elegance and safety of Swift

Unleashing the real power of Core Data with the elegance and safety of Swift Dependency managers Contact Swift 5.4: iOS 11+ / macOS 10.13+ / watchOS 4

John Estropia 3.7k Jan 9, 2023
JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box.

JustPersist JustPersist is the easiest and safest way to do persistence on iOS with Core Data support out of the box. It also allows you to migrate to

Just Eat 167 Mar 13, 2022
A minimalistic, thread safe, non-boilerplate and super easy to use version of Active Record on Core Data.

Skopelos A minimalistic, thread-safe, non-boilerplate and super easy to use version of Active Record on Core Data. Simply all you need for doing Core

Alberto De Bortoli 235 Sep 9, 2022
Super awesome Swift minion for Core Data (iOS, macOS, tvOS)

⚠️ Since this repository is going to be archived soon, I suggest migrating to NSPersistentContainer instead (available since iOS 10). For other conven

Marko Tadić 306 Sep 23, 2022
HitList is a Swift App shows the implementation of Core Data.

HitList HitList is a Swift App shows the implementation of Core Data. It is the demo app of Ray Wenderlich's tech blog. For details please reference G

Kushal Shingote 2 Dec 9, 2022
A type-safe, fluent Swift library for working with Core Data

Core Data Query Interface (CDQI) is a type-safe, fluent, intuitive library for working with Core Data in Swift. CDQI tremendously reduces the amount o

null 31 Oct 26, 2022
100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer

DATAStack helps you to alleviate the Core Data boilerplate. Now you can go to your AppDelegate remove all the Core Data related code and replace it wi

Nes 216 Jan 3, 2023
This project server as a demo for anyone who wishes to learn Core Data in Swift.

CoreDataDemo This project server as a demo for anyone who wishes to learn Core Data in Swift. The purpose of this project is to help someone new to Co

null 1 May 3, 2022
A type-safe, fluent Swift library for working with Core Data

Core Data Query Interface (CDQI) is a type-safe, fluent, intuitive library for working with Core Data in Swift. CDQI tremendously reduces the amount o

null 31 Oct 26, 2022
JSQCoreDataKit - A swifter Core Data stack

JSQCoreDataKit A swifter Core Data stack About This library aims to do the following: Encode Core Data best practices, so you don't have to think "is

Jesse Squires 596 Dec 3, 2022
QueryKit, a simple type-safe Core Data query language.

QueryKit QueryKit, a simple type-safe Core Data query language. Usage QuerySet<Person>(context, "Person")

QueryKit 1.5k Dec 20, 2022
Core Data code generation

mogenerator Visit the project's pretty homepage. Here's mogenerator's elevator pitch: mogenerator is a command-line tool that, given an .xcdatamodel f

Wolf Rentzsch 3k Dec 30, 2022
Super Awesome Easy Fetching for Core Data!

MagicalRecord In software engineering, the active record pattern is a design pattern found in software that stores its data in relational databases. I

Magical Panda Software 10.9k Dec 29, 2022
A feature-light wrapper around Core Data that simplifies common database operations.

Introduction Core Data Dandy is a feature-light wrapper around Core Data that simplifies common database operations. Feature summary Initializes and m

Fuzz Productions 33 May 11, 2022
The Big Nerd Ranch Core Data Stack

BNR Core Data Stack The BNR Core Data Stack is a small Swift framework that makes it both easier and safer to use Core Data. A better fetched results

Big Nerd Ranch 561 Jul 29, 2022
Example repo of working with Core Data in a SwiftUI application

CoreData in SwiftUI This repository serves many purpose. But mostly so I can experiment with Core Data in SwiftUI, and also so I can use it show my ap

Donny Wals 4 Jan 30, 2022