Unit Testing CoreData Tip: The Singleton

It’s been a while since I was deep into CoreData, but here I am again. And this time, I’m writing proper unit tests.

Things were going pretty well – I had about 50 test cases with a few related asserts in each – until I started messing with saving, and fetching tests. I ran into some odd behavior where sometimes a particular test would pass, other times fail with different results in one assertion. All I was doing was creating a managed object, setting a relationship, saving, and reading back to check for proper order. Pretty trivial stuff.

I looked deeper.

If I ran just that one test case by itself, it would always pass. If I ran “All Tests”, it would always fail. Sometimes I would get several fetched objects when only one was expected. Sometimes those would be in different orders.

As I dug deeper, I attempted to reset my context on each test case

[self.managedObjectContext reset];

No luck.

To this point, my managedObjectContext has been a singleton – to follow the pattern of the rest of the appellation. I had a hunch the problem might be there – especially if multiple tests are running (concurrently, even?).

+(instancetype)inMemoryManager {
    static DataManager *sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[DataManager alloc] init];

        NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[sharedInstance managedObjectModel]];

        NSError *error;
        if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error]) {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);

        sharedInstance.persistentStoreCoordinator = persistentStoreCoordinator;

    return sharedInstance;

I tried creating a separate for-testing-only manager that creates a new stack each time so I could hopefully avoid these apparent concurrency issues.

+(instancetype)inMemoryManagerForTesting {
    DataManager *dataManager = [[DataManager alloc] init];
    NSPersistentStoreCoordinator *persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[dataManager managedObjectModel]];

    NSError *error;
    if (![persistentStoreCoordinator addPersistentStoreWithType:NSInMemoryStoreType configuration:nil URL:nil options:nil error:&error]) {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    dataManager.persistentStoreCoordinator = persistentStoreCoordinator;

    return dataManager;

That seems to do the trick, though I would have preferred sticking with the singleton. Don’t use CoreData stack singletons. Turns out @orta suggests the same [tweet] [blog post].

Tagged , ,

iOS TDD (Test Driven Development) – Convincing Myself

By no means is TDD (Test Driven Development) a new concept; I’ve known about it for years. I had sone some unit testing on projects prior, they became an integral part of routine when I started consulting for HP’s Software R&D lab. We’ve been very good about testing out all the important logic of the application, save automated functional testing of the UI (more on that in another post).

This post is really about TDD, not convincing you to unit test your code (something you should be doing). Actually, I’m not a diehard TDD fanatic. Rather I use principles of testing first before writing application logic. I don’t want to get stuck the pedantics of true TDD development.

My journey, if you will, started as I had a turning point in two projects for Pivotal Action that convinced me. The first project involved a bit of interplay between iBeacons (CLBeacon) and networking, which would be impractical to manually test with physical hardware. The second project involves a lot of transformations being applied to objects, and some networking. In both cases, relying on rather extensive unit tests could ensure I wasn’t breaking functionality with new features.

My general approach involves a few simple practices:

  1. Create a mock data set for input. I often use JSON files because it’s easily readable, and you can use the same data on multiple tests if you need. Also helpful if you’re testing mock network response data
  2. Create a test data set, or scenario. First pass, go with the “golden path” – the best case scenario
  3. Determine what your desired outcomes are in a best-case scenario
  4. Create separate test cases for each kind of data you may have to deal with. Again – start with the best case scenario
  5. Write some logic code to either transform data, or respond to it
  6. Go back to step 1 and create a new set of data representing one type of problem, or family of very similar problems. This could be malformed data, error codes from API services, etc. as well as common problems : out-of-bounds errors, off by one, nil, and others.
  7. Keep repeating 2-5 until you’ve exhausted just about every scenario you can reasonably think of.

This may seem boring and repetitive, but I assure you that thoroughly testing your logic will uncover holes in your implementation before you even start writing application and UI code. You’re also more likely to survive refactoring unscathed if you have extensive unit tests covering the changing code. I recently benefitted from this when I converted a set of model classes over to a CoreData stack. It wasn’t a perfect 1:1 refactor, but it uncovered some places where I had to adapt my expectations and logic so that the transformations would be the same in the end.

I’m not perfect at this, but I can say that doing unit testing before really getting into the guts of an application has saved me a lot of work farther down the road. I also have more confidence that changes I make aren’t breaking existing functionality. Give it a shot.

Tagged ,

Rest and Vacation for Your Mind

I don’t know about you, but I often forget just how much I can enjoy and actually need time off to rest from work. I recently took ten days (mostly) off to be with family and explore the great outdoors. After returning to work, I feel recharged, and fresh with ideas; even colleagues have made note.

I need to remember this for next time.  Taking the time away allows your brain to recharge, change gears, and get away from the routines of work. Refresh.


iPhone 6 Screen Resolution, Points, and Pixels Explained

iPhone 6 Screens Demystified on PaintCode

There were a lot of questions surrounding the rumored iPhone 6 display resolution. A few had well-reasoned extrapolations based on conjecture, but ultimately we had no idea. Now that the hardware is public and our iOS 8 SDKs are gold master, we finally have the numbers. And…. they’re not what we expected.

Yup – 3x graphics are there for the iPhone 6 Plus, but by the time those images hit the screen, they’ve been down sampled by about 15%. I’m sure the 6 Plus screen looks absolutely delicious, but I can’t imagine what that scaling factor is actually going to look like.  Or maybe I do. Having owned a retina Macbook Pro, I’m familiar with scaling on the retina display. It’s actually hardly noticeable. Maybe if I get up close I could see some sort of issue, but I haven’t yet.

We have higher resolution on-screen now, but the UI should be about the same size as it always has; it’s important to Apple that touch just works.

Tagged ,

Initial Reactions: Apple Watch, Apple Pay, iPhone 6

Today’s Apple event flew by, and for good reason – it was jam-packed full of some goodies.

 iPhone 6, 6 Plus

I hate to say it, but I think the iPhone 6 is the least interesting piece of news from the Apple Event. But, that doesn’t mean these are un-interesting devices. Of course, we’re all excited about having a larger screen (I hear you, Android fans). The specs look great – full sRGB gamut, wide viewing angles. The camera also received some nice bumps: new image stabilization & autofocus improvements, better sensors, etc. Processor, GPU… all what you would expect from a next-generation phone. I think the design is nice, but nothing extraordinary. Maybe I’ll feel differently once I get my hands on one.

Apple Watch

Technically Groundbreaking? I wouldn’t say so – there have been other smart watches before it. Groundbreaking in the way Apple does things – yup. It’s clear Apple spent a ton of time on the user interface – both software (panning, tapping, etc) and hardware (crown, buttons, etc). As pointed out in the presentation, there are metaphors that we’re used to on a phone that won’t work on the watch. Pinch to zoom was one of them. This is where Apple shines – by practicing restraint (cue the “thousand ‘no’s for every yes quote).

I’m eager to see the Watch SDK. Even with the minimal features they demonstrated on stage, I can think of numerous applications complemented by the Watch.

Apple Pay

This was the most recent / late-to-the-game rumor to come out, but it’s brilliant. This, I believe, is where Apple has the most room to disrupt an industry. Sure, the watch is pretty cool, but that seems more an evolution on how things are done. With Apple Pay, we’re now moving away from plastic as identifier to biometrics and person as identifier. I suspect Android solutions will be close behind (even Google’s failed attempts at Google Wallet), which when taken together as a whole, represent a monumental paradigm shift in how we pay for things. I particularly like the focus on the payment transaction – *beep* paid for. All the payment source is kept secret from the retailer (so some scoundrel waiter doesn’t swipe your CC at the restaurant), and Apple doesn’t care to know what you purchased. Apple as opposed to Google and Amazon, is not in the advertising business, and they keep driving that point home. Your information is safe with us. Given Apple’s consistent approach to protecting consumers (e.g. AppStore), it’s a believable (as in trustworthy) statement.


Overall, a great announcement. There’s a lot to look forward to in the coming weeks and months. We’ll see how this has all panned out in a year. Now, if you’ll excuse me, I’m greasing up my card for a new phone and watch purchase.

New iTunes Connect “Processing” Purgatory and Usability Issues

The new iTunes Connect has only been out a few days. Overall, I think it’s probably better than the old version – there are just a few things to get used to. It seems there’s a noticeable lack of communication within the new web app – enough that I filed a couple of bug reports.

Two surround the situation where you have uploaded a binary to iTunes connect. The first issue – you are not allowed to re-upload a binary with the same version and build number. However, there is no way to remove the old one. The second is a little less obvious: Uploading the new binaries will place them in a “Processing” state with no indication about what is happening. Fearing something had gone wrong, I tried the upload a few more times with different build numbers & formats – all went to “Processing” with no icon – only the version, build number, and upload timestamp. None of them were available to select so I could submit for App Store review. Xcode said everything was OK, Application Loader said everything was fine. An hour later, all four builds were processed. Thanks, I guess.

No matter the technical process, there are a few key points of communication they missed out on:

  • There’s no indication what “Processing” actually does, or how long it should take. Minutes, hours, days?
  • There’s no explanation about uploading “duplicate” binary version/build numbers until you’ve actually failed
  • Sometimes there are errors saving metadata – generic error message – users should be informed about what entry was wrong, and how to correct the problem
  • In general, I see no clear links to documentation, which would have been helpful
  • Xcode’s messaging is not consistent with Application Loader, which is also inconsistent with the iTunes Connect website.

I believe these issues are easily addressed, however they sure demonstrate how usability/experience is affected when a few pieces of key information is missing.

Tagged , ,

The Human Connection

From Brent Simmons’ post: Why I Love Indies and You Do Too:

I’ve noticed something obvious about popular music — it’s almost never instrumental. There’s always a human voice singing a melody. We humans love human voices.

That’s what we get from indies that we don’t get from corporations. We get that human voice and the emotional connection that goes with it.

Knowing that I’m using software by individual developers or small teams, creates a special connection to real people that doesn’t come from the likes of Photoshop, Office, or any other Large Corp application. Indies, and those who wish they were, care about things like craftsmanship, creativity, human connection, dedication to the process, and the ritual. We are feeling the collective pang of defeat little-by-little as it all seems to slip through our fingers. Holding onto the “Indie” hope is becoming more like grasping the sand – we don’t quite know what to do as it slips through our fingers. If nothing is done, we’ll be left holding nothing.

I don’t mean to be doom and gloom. I think there is plenty of work out there – some of it rewarding. It’s just that doing your own thing, on your own product, on your own schedule is a dimmer possibility than it seemed in the past. I don’t think it has to be over.

So by all means – get a job or consult, if that’s what keeps the lights on. Spend your free time doing what you love to do. Create. Craft. Build & Run. Nobody is saying you have to do it  full-time to be a success. Success is paying your bills, savings, taking care of family, and may more things. Icing on the cake is making great things for people so their lives can be just a little bit better – because you stepped up to the plate and made it happen.

Tagged ,

July 2014: We Noticed Indie Died

It seems July 2014 may go down as the month when we realized being an indie (iOS) developer is no longer feasible. It’s not that something suddenly happened, rather, we collectively realized the same thing: there’s no way to make a living doing this.  Rather than making a living off of developing one or two apps, we need to find another source of income and do this on the side. It’s the only way.

Here are some recent posts by notable developers in the community. They hit on a few different woes, and points. Some implore we approach this whole thing from another direction.


A Candid Look at Unread’s First Year

More on iOS Indies

Shopster 2013

iOS Indie Game Numbers

App Rot


The iOS Indie That Could

Trials and Updates are Still Dead

On Pricing More

App Store Realities

Why I Left Indie Development

Where are the Indie iOS Developers You Ask?

The Mobile Software Disaster

Another Non-Indie Developer App Story

The New Indie


I fall right in line with many of the experiences expressed in the aforementioned links. In the early days of Pivotal Action, we were starry-eyed at the possibility of creating something great that people liked, with the “reasonable” hopes of being successful. We started off with Completion, and later went on to work on a new project, Pixd, that never shipped (though it was close-ish). By the time we more or less gave up on Pixd, I think we had realized the return on our time investment was unlikely to pay off. Even as the dust was still settling with Completion, we knew we couldn’t quit the consulting side of the business – it was paying the bills.

[UPDATE] I’ve added additional links showing more experiences and perspective on the indie situation

Tagged , ,

Apples Answer on Upgrade Pricing

From David Smith

Logic Pro X is a Major with a capital M update to their professional audio editing suite. It appears to represent a significant investment in both time and resources. So how is it being sold, especially to people who already paid $200 for the previous version Logic Pro 9? It is a separate app download with a full cost purchase. No upgrades, no introductory pricing, just straight forward sale.

I’d say that this is the best indication of Apple’s intentions and expectations for the App Stores going forward.

via Apples Answer on Upgrade Pricing – David Smith.

I know people are offended by the pricing, but the reasonable side of me wonders how they can be so offended. Perhaps the “race to the bottom” on the mobile side has poisoned us into believing software should be very cheap (or free).

Tagged ,

Raising the Bar on Real

Apple Outsider » Real.

We don’t need the deception of “photorealism” anymore. Despite the loss of these tricks, iOS 7 feels more real. The parallax effect conveys an entire living world under that glass, not just abstract pictures and icons.

On the surface, iOS 7 looks like a refreshed UI, and nothing more. But digging deeper and looking closer, we have entirely new channels of user experience and interaction design opened up to us – not because we can (we always could) – but because it’s the new status quo. The bar has been raised.

Tagged , , ,

Get every new post delivered to your Inbox.

Join 392 other followers