• This repository has been archived on 24/Nov/2021
  • Stars
    star
    215
  • Rank 178,001 (Top 4 %)
  • Language
    Swift
  • License
    Other
  • Created about 10 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

100% Swift Simple Boilerplate Free Core Data Stack. NSPersistentContainer

DATAStack

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 with an instance of DATAStack (ObjC, Swift).

  • Easier thread safety
  • Runs synchronously when using unit tests
  • No singletons
  • SQLite and InMemory support out of the box
  • Easy database drop method
  • Shines with Swift
  • Compatible with Objective-C
  • Free

Table of Contents

Running the demos

  • Clone the repository
  • Open the Demo.xcodeproj
  • Enjoy!

Initialization

You can easily initialize a new instance of DATAStack with just your Core Data Model name (xcdatamodel).

Swift

let dataStack = DATAStack(modelName:"MyAppModel")

Objective-C

DATAStack *dataStack = [[DATAStack alloc] initWithModelName:@"MyAppModel"];

There are plenty of other ways to intialize a DATAStack:

  • Using a custom store type.
let dataStack = DATAStack(modelName:"MyAppModel", storeType: .InMemory)
  • Using another bundle and a store type, let's say your test bundle and .InMemory store type, perfect for running unit tests.
let dataStack = DATAStack(modelName: "Model", bundle: NSBundle(forClass: Tests.self), storeType: .InMemory)
  • Using a different name for your .sqlite file than your model name, like CustomStoreName.sqlite.
let dataStack = DATAStack(modelName: "Model", bundle: NSBundle.mainBundle(), storeType: .SQLite, storeName: "CustomStoreName")
  • Providing a diferent container url, by default we'll use the documents folder, most apps do this, but if you want to share your sqlite file between your main app and your app extension you'll want this.
let dataStack = DATAStack(modelName: "Model", bundle: NSBundle.mainBundle(), storeType: .SQLite, storeName: "CustomStoreName", containerURL: sharedURL)

Main Thread NSManagedObjectContext

Getting access to the NSManagedObjectContext attached to the main thread is as simple as using the mainContext property.

self.dataStack.mainContext

or

self.dataStack.viewContext

Background Thread NSManagedObjectContext

You can easily create a new background NSManagedObjectContext for data processing. This block is completely asynchronous and will be run on a background thread.

To be compatible with NSPersistentContainer you can also use performBackgroundTask instead of performInNewBackgroundContext.

Swift

func createUser() {
    self.dataStack.performInNewBackgroundContext { backgroundContext in
        let entity = NSEntityDescription.entityForName("User", inManagedObjectContext: backgroundContext)!
        let object = NSManagedObject(entity: entity, insertIntoManagedObjectContext: backgroundContext)
        object.setValue("Background", forKey: "name")
        object.setValue(NSDate(), forKey: "createdDate")
        try! backgroundContext.save()
    }
}

Objective-C

- (void)createUser {
    [self.dataStack performInNewBackgroundContext:^(NSManagedObjectContext * _Nonnull backgroundContext) {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"User" inManagedObjectContext:backgroundContext];
        NSManagedObject *object = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:backgroundContext];
        [object setValue:@"Background" forKey:@"name"];
        [object setValue:[NSDate date] forKey:@"createdDate"];
        [backgroundContext save:nil];
    }];
}

When using Xcode's Objective-C autocompletion the backgroundContext parameter name doesn't get included. Make sure to add it.

Clean up

Deleting the .sqlite file and resetting the state of your DATAStack is as simple as just calling drop.

Swift

self.dataStack.drop()

Objective-C

[self.dataStack forceDrop];

Testing

DATAStack is optimized for unit testing and it runs synchronously in testing enviroments. Hopefully you'll have to use less XCTestExpectations now.

You can create a stack that uses in memory store like this if your Core Data model is located in your app bundle:

Swift

let dataStack = DATAStack(modelName: "MyAppModel", bundle: NSBundle.mainBundle(), storeType: .InMemory)

Objective-C

DATAStack *dataStack = [[DATAStack alloc] initWithModelName:@"MyAppModel"
                                                     bundle:[NSBundle mainBundle]
                                                  storeType:DATAStackStoreTypeInMemory];

If your Core Data model is located in your test bundle:

Swift

let dataStack = DATAStack(modelName: "MyAppModel", bundle: NSBundle(forClass: Tests.self), storeType: .InMemory)

Objective-C

DATAStack *dataStack = [[DATAStack alloc] initWithModelName:@"MyAppModel"
                                                     bundle:[NSBundle bundleForClass:[self class]]
                                                  storeType:DATAStackStoreTypeInMemory];

(Hint: Maybe you haven't found the best way to use NSFetchedResultsController, well here it is.)

Migrations

If DATAStack has troubles creating your persistent coordinator because a migration wasn't properly handled it will destroy your data and create a new sqlite file. The normal Core Data behaviour for this is making your app crash on start. This is not fun.

Installation

DATAStack is available through CocoaPods. To install it, simply add the following line to your Podfile:

use_frameworks!

pod 'DATAStack', '~> 6'

DATAStack is also available through Carthage. To install it, simply add the following line to your Cartfile:

github "SyncDB/DATAStack" ~> 6.0

Be Awesome

If something looks stupid, please create a friendly and constructive issue, getting your feedback would be awesome.

Have a great day.

Author

Elvis Nuรฑez, @3lvis

License

DATAStack is available under the MIT license. See the LICENSE file for more info.

More Repositories

1

Sync

JSON to Core Data and back. Swift Core Data Sync.
Swift
2,553
star
2

Form

The most flexible and powerful way to build a form on iOS
Objective-C
1,648
star
3

Networking

Swift HTTP Networking with stubbing and caching support
Swift
1,344
star
4

Viewer

Image viewer (or Lightbox) with support for local and remote videos and images
Swift
536
star
5

SectionScrubber

A component to quickly scroll between collection view sections
Swift
188
star
6

FormTextField

UITextField with support for formatters and input validators
Swift
185
star
7

DATASource

Core Data's NSFetchedResultsController wrapper for UITableView and UICollectionView
Swift
106
star
8

CardStack

DEPRECATED
Swift
37
star
9

Hex

Hex support for UIColor, all in Swift
Swift
24
star
10

app-template

Swift storyboard-less well structured iOS app template
Swift
17
star
11

DateParser

Simple ISO 8601 and Unix timestamp Swift date parser
Swift
15
star
12

DATAFilter

Filter inserts, updates and deletions from your JSON response
Swift
15
star
13

NetworkActivityIndicator

A library that helps managing the network activity indicator state
Swift
11
star
14

PaginatedScrollView

Paginated UIScrollView, a simple UIPageViewController alternative written in Swift.
Swift
10
star
15

AppNetDemo

Sync's Swift App.Net Demo [Deprecated]
Swift
9
star
16

MD5

[DEPRECATED]
Swift
6
star
17

DATAFastQuery

The fastest way to query Core Data
Swift
5
star
18

ControllerContainer

View Controller Containment for humans
Swift
5
star
19

iOS-playbook

Guidelines and best practices for excellent iOS apps
4
star
20

StoryboardDemo

A demo project to show how to use DATASource and DATAStack with Storyboards
Swift
4
star
21

Dream

The future of networking and persistency on iOS, OS X, watchOS and tvOS
Swift
4
star
22

JSON

JSON made so simple, it hurts
Swift
4
star
23

NestedXibs

Sample project on how to embed a xib inside another xib.
Swift
2
star
24

OfflineCRUDDemo

Swift
2
star
25

SyncDemo

A simple demo of how to set up and use Sync to fetch data from the network and display it in a UITableView
Swift
2
star
26

ios-mvc

Example of Model-View-Controller in iOS instead of Model-View-ViewController
Swift
2
star
27

Pinwheel

Swift
2
star
28

Toyay

To Do iOS app
Swift
2
star
29

chromeless-ios

An app that wraps any website in a native container
Swift
1
star
30

Notification

Swift
1
star
31

SimulatorCheck

Check for code running on the Xcode simulator
Ruby
1
star