SuperRecord an ActiveRecord implementation in Swift

All the media buzz around swift seems to be having some tangible effect. I won’t go into the opinionated slaw of Swift VS Objective-C VS Swift VS XYZ here :). Many of you know I freelance in the iOS space around London and beyond for SuperArmstrong and one of my recent clients asked me to work on a greenfield project to replace a very old wrapped web app they had. When we got down to the nitty gritties, one of their few requirements was that it should be written in Swift. My jaw did drop a little… considering this was about 20 days after Swift had first been publicly announced. After some conversation, we came to the mutual conclusion that they were brave.

Like many of the apps I work on, this project relied heavily on CoreData, as a convenience I decided i’d try out a library that I have a lot of respect for (even though its had its challenging moments) “MagicalRecord”, having only done organic CoreData for the past few years. As you probably know, Objective-C and Swift can sit alongside in a project and work in unison… however, not all the interoperability is 100% sound. I soon started to endure strange bugs and thanks to the incompleteness of Swift lldb support at the time (especially when mixing with Objective-C) these bugs soon became quite difficult to track down.

The most annoying was this:

let entityDescription = NSEntityDescription.entityForName("Pokemon", inManagedObjectContext: context)

Although harmless… this would actually fail when trying to insert an entity of that description into your managed object context. The culprit here? the NSString to String bridging (or vice versa).

To get around this bug (which I won’t go into too much detail) I began using:

let entityName = "Pokemon" as NSString
let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)

Performing a forced downcast to NSString. So great, now it works… However, many of the MagicalRecord finders and helpers I was using, would not have these forced downcasts as they came from the Objective-C world. I first forked MagicalRecord, after delving into the source-code, making many changes for better Swift support, fixing some threading irregularities I then realised I was putting a lot of work into making something work that had more functionality than I required at the time. So I embarked on making a Swift ActiveRecord style “companion” to CoreData.

The reason I say “companion” and not “wrapper” is that I didn’t want to abstract away CoreData too much or remove the power from the hands of the developer. I wanted to make the developer’s life easier, whilst maintaining their flexibility.

I’d much rather do something like this:

let pokemon = Pokemon.createNewEntity() as Pokemon

and avoid the above lines + more.

Thereby SuperRecord was born. The original goals for SuperRecord were simple.

  1. Give me the ActiveRecord style finders I crave, optimise them, keep my application level code tidy, but still performant.
  2. Rather than me typing out the same code in each project to handle batch updates on my UITableView and UICollectionView classes, have a special “one size fits all” class that will act as your NSFetchedResultsControllerDelegate, providing “safe” batch updated to your reusable views.
  3. Additionally, I didn’t wanna have to spend too much time creating NSFetchedResultsControllers all the time either, so I added some helpers for this too.
  4. Be written in Swift, keeping the public API’s simple and stable, but changing the implementation as Swift changed and moved with updates.

In late October 2014 whilst still very much a work in progress, I released the first public version and it was featured in the great iOS Dev Weekly newsletter. I decided to release it early as I saw a lot of discussion around CoreData and Swift and thought there’d be a lot of people interested in this OSS effort, so we could build up a good toolset as a community. I’m still the only maintainer… (not by choice) but its early days :).

Below is some extract from the README.md but I suggest you head over to the project on github for more information and feel free to checkout the demo project also on github which shows how to use the safe batched updates along with some other common tasks.

 

Core Files

  • NSManagedObjectExtension.swift This extension is responsible for most of the “finder” functionality and has operations such as deleteAll()findOrCreateWithAttribute()createEntity() and allows you to specify your own NSManagedObjectContext or use the default one (running on the main thread).
  • NSFetchedResultsControllerExtension.swift In constant development, this Extension allows the easy creation of FetchedResultsControllers for use with UICollectionView and UITableView that utilise the SuperFetchedResultsControllerDelegate for safe batch updates.
  • SuperFetchedResultsControllerDelegate.swift heavily inspired by past-projects i’ve worked on along with other popular open source projects. This handles safe batch updatesto UICollectionView and UITableView across iOS 7 and iOS 8. It can be used on its own with your NSFetchedResultsController or alternatively, its automatically used by the NSFetchedResultsControllerExtension methods included in SuperRecord.
  • SuperCoreDataStack.swift a boilerplate experimental main thread CoreData stack. Can be used either as a sqlite store or in memory store. Simply by calling SuperCoreDataStack.defaultStack() for SQLite or SuperCoreDataStack.inMemoryStack() for an in memory store. Of course you have access to your context .context / .saveContext()

Usage

Create a new Entity

Assuming you have an NSManagedObject of type “Pokemon” you could do the following

let pokemon = Pokemon.createNewEntity() as Pokemon

Please add @objc(className) above the class name of all your NSManagedObject subclasses (as shown in the demo project) for now. Better support will be coming in the future.

Creating an NSFetchedResultsController

This feature is currently in progress with basic support so far, in future versions, sorting and sectionNameKeyPath’s will be supported. Until then you can create your own NSFetchedResultsController, however, if you have no need for the above missing functionality then simply use

lazy var fetchedResultsController: NSFetchedResultsController = self.superFetchedResultsController()

func superFetchedResultsController() -> NSFetchedResultsController {
return NSFetchedResultsController.superFetchedResultsController("Pokemon", tableView: tableView)
}

With Pokemon being the entity name of your NSManagedObject.

Delete Entities

I’m planning on adding much more powerful functionality around Delete soon, such as deleteAllWithPredicate() or deleteEntity(), right now all that is available is

Pokemon.deleteAll()

Method Listing

This isn’t an exhaustive list of all methods and classes, however it includes some of the most useful ones.

  • NSManagedObjectExtension
  • findAllWithPredicate(predicate: NSPredicate!, context: NSManagedObjectContext) -> NSArray
  • findAllWithPredicate(predicate: NSPredicate!) -> NSArray
  • deleteAll(context: NSManagedObjectContext) -> Void
  • deleteAll() -> Void
  • findAll(context: NSManagedObjectContext) -> NSArray
  • findAll() -> NSArray
  • findFirstOrCreateWithPredicate(predicate: NSPredicate!) -> NSManagedObject
  • findFirstOrCreateWithPredicate(predicate: NSPredicate!, context: NSManagedObjectContext) -> NSManagedObject
  • createNewEntity() -> NSManagedObject
  • findFirstOrCreateWithAttribute(attribute: NSString!, value: NSString!, context: NSManagedObjectContext) -> NSManagedObject
  • findFirstOrCreateWithAttribute(attribute: NSString!, value: NSString!) -> NSManagedObject
  • NSFetchedResultsControllerExtension
  • superFetchedResultsController(entityName: NSString!, collectionView: UICollectionView) -> NSFetchedResultsController
  • superFetchedResultsController(entityName: NSString!, tableView: UITableView) -> NSFetchedResultsController

NSFetchedResultsControllers created using this method will automatically handle safe batch updates.

Developer Notes

This whole project is a work in progress, a learning exercise and has been released “early” so that it can be built and collaborated on with feedback from the community. I’m using it in a project I work on everyday, so hopefully it’ll improve and gain more functionality, thread-safety and error handling over time.

The next key things to be worked on are Optionality (as this has changed in every Swift BETA), the CoreDataStack, adding more finders with more functionality and improving the NSFetchedResultsControllerExtension.

 

 

Mockacino a lightweight ruby/sinatra API Mocking script

Hi Guys, so i’ve been working on a new app recently for a client of mine, currently there is no API… so in the meantime I decided to knock up a quick few lines of ruby to get a mocking api up and running… to explain this better, I need not do more than paste my README.md here.. Enjoy 🙂

Mockacino

A very simple and easy to use MOCK API server that serves static JSON written in ruby/sinatra.


NOTE: This is a super simple, super fragile MOCKING SERVER Intended so you can test routes and mock an API with static jso whilst you’re still building the real production API. DO NOT EVER use this in production… Seriously. It breaks a lot and will if you try… DONT. Absolutely 0 effort went into it, therefor 0 Warranty. Use if you dare.

DOCS:

Folder structure defines API calls…. return.json is what gets served.

site_root ->;
    [ http method ] ->; [ api call route ] ->; [ json response contents of call return.json ] 

e.g.

site_root ->;
    GET ->; users ->; return.json
    POST ->; users ->; create ->; return.json

If you have static assets you wanna reference in the json, plonk them in the ASSETS folder

e.g.

site_root ->; file.jpg

You can call http://yourhost:port/ASSETS/file.jpg

Here’s the directory structure of the sample project included here

mockacino.rb  
./site_root/ASSETS
./site_root/GET
./site_root/POST
./site_root/GET/sheep
./site_root/GET/sheep/create
./site_root/GET/sheep/return.json
./site_root/GET/sheep/create/return.json

Which supports calls like…

http://localhost:4567/sheep
http://localhost:4567/sheep/create

And gives responses from the static result.json file like…

{
    "sheep": [
        {
            "id": "1234",
            "name": "Dolly Two",
            "url": "http://mike.kz/sheep1234",
            "assets": {
                "small_image": "http://cloned.sheep.com/ASSETS/small.jpg",
                "large_image": "http://cloned.sheep.com/ASSETS/large.jpg"
            }
        }
    ]
}

Usage:

gem install sinatra
ruby mockacino.rb
 

Swift the new Language for writing Cocoa and Cocoa Touch Apps

swift programming language

Introducing Swift

I’ve been at WWDC 2014 all week and one of the major announcements from Apple was a new programming language they’ve been working on named “Swift”, immediately it flashed me back to a really old WWDC where they announced an experimental language they were playing with named “Dylan” but I could be wrong.

Swift attempts to deliver a fast modernised language that looks and behaves as an interpreted language such as Ruby or Python but has all the power of a compiled language such as C++/Objective-C. From what i’ve seen on the interweb and twitter, there seems to have been a mixed reception from developers, but overall its looking more positive than not… My stance is… i’m gonna read more than 60 pages and wait more than 48 hours before declaring either my love or hate for Swift :)… If you’ve seen the blogosphere lately, you’ll understand what I mean.

Apple have released a publicly available (so i’m guessing not under NDA) Swift book on the iBook Store thats lengthy, doesn’t assume you’re an 8 year old and gives a decent overview of the Swift programming language, in what seems is from a “answer all of your questions and thoughts” approach, with some examples and exercises along the way.

I’ve attended the Swift labs almost everyday this week armed with questions, thoughts, suggestions and generally the engineers have been great at responding to everything. As a result i’ve filed radars, been convinced i’m not crazy and had some insight into the future of the language.

My main bone of contentions so far are:

  • No sensible/pretty way to selectively expose method A vs method B.
  • The threading model is still a little undefined and incomplete.
  • Autocomplete and LLDB seem to still be a very much work in progress.
  • Downcasting syntax is overly verbose.
  • Did I do it wrong? or did Xcode just shit itself?

However having said that, Swift was released early to us the developers, in order to get feedback/suggestions and help Apple build it to how we want… lets not forget, i’ve had (at the time of writing) 96 hours experience in Swift and its only been public for around the same amount of time… so a lot is likely to change.

What I like so far:

  • Generally a nicer more modern syntax
  • Less “falling back” to C for common things
  • Less unnecessary verbosity *(most the time)
  • Pretty seamless “bridging”/”interoperability” (or whatever the term should be) to existing Objective-C code
  • Namespacing, Modules & Frameworks
  • Explicit typing support with some intelligence from the compiler too
  • An emphasis on “tell the compiler as much as possible”

As soon as I figure out whether or not we’re allowed to talk about more, i’ll go into more detail on some of these points and post some sample code. I’m currently working on an iOS Framework written in pure swift that I’m sure people will enjoy, i’ll be posting it on GitHub in the near future here it is now, but its probably far away from prime time and perhaps a little useless 🙂 but a great way to learn Swift!

As always, thoughts and criticisms should be constructive and not defamatory and furthermore, have your own opinion, no one you follow on twitter is an expert on this yet 🙂 so don’t be afraid to voice your opinions and join in the healthy discussion.

If you wanna chat about it more, i’m @ArmstrongAtWork on twitter.

 

 

 

How to setup Ruby on Rails on Ubuntu Linux

There are a lot of guides that do exactly the same as what i’m about to write about… the reason for this quick blog post is mostly a brain dump for myself.. but also because I always struggle to find up to date info for all of this in one place… and there are always gaps… So here goes! by the end of this short tutorial, you should have not only a working rails and ruby installation, running as a user, but also a ruby on rails hello world! whaaaaaat. …