Pawan Poudel

Read this first

Fixing Core Data Concurrency Violations

With iOS 8.0 Apple gave us access to a tool for tracking down code that violates Core Data concurrency rules. This post outlines how to setup Xcode so that you can identify and fix the faulty code.

Background

According to the Core Data concurrency rule, each thread must have its own managed object context. This is because NSManagedObjectContext and NSManagedObject, two most fundamental objects in Core Data, are not thread safe. They shouldn’t be initialized in one thread and accessed from a different thread.

Multi-Context Core Data Stack

Let’s explore this concept of thread confinement further through a specific example. I have created a sample app to demonstrate how to track and fix these violations. Go ahead and clone the repo from Github or browse the code online to follow along. Figure below shows the Core Data stack for the sample app.

core_data_multi_context_stack.png

This setup is inspired by a wonderful...

Continue reading →


Enumerating Collections in Objective-C

One question I often get asked is what’s the best way to enumerate the contents of a collection in Objective-C. I thought I would list them all in this blog post as a reference.

There are four different ways to enumerate a collection in Objective-C. They are listed below in the order I recommend them.

1. Block-Based Enumeration

Block-based enumeration provides the fastest way to enumerate a collection. Here is an example showing how to enumerate an NSArray:

[array enumerateObjectsUsingBlock:
  ^(id object, NSUInteger index, BOOL *stop) {
    if ([self stopEnumerating]) {
      *stop = YES;
    }
}];

2. Fast Enumeration

for (id item in collection) {
  // ...
}

3. NSEnumerator

for (id item in [array reverseObjectEnumerator]) {
  // ...
}

4. C for Loop

int count = [array count];
for (int index = 0; index < count; index++) {
    id item = [array objectAtIndex:index];
    // ...
...

Continue reading →


Transitioning to Swift

iOS community has enthusiastically accepted Swift as the successor to Objective-C. iOS developers feel excited when they get to implement a new app or a feature in Swift. The open-source community has been voraciously contributing to the ever growing collection of third-party libraries written in Swift. Apple has also made it clear that it will be investing heavily in the advancement of Swift. WWDC is right around the corner and I can’t wait to find out what new features we will get from Cupertino.

Because of all these reasons, you might have finally been able to convince your team to transition towards Swift. Here are some tips that might be helpful during the transition.

Training

  • Ideally you want everyone in your team to get up to speed with Swift quickly by reading books, blog...

Continue reading →


Mobile Testing Strategy

I view testing as a spectrum. At one end of this spectrum all testing is done manually. At the other end all tests are automated. Somewhere between these two extremes lies a good balance. To find that balance, we need to be able to identify parts of an application that can be effectively tested by the right type of test. If a system is designed with a good separation of concerns in mind by creating explicit boundaries around the core business logic, it becomes much easier to identify those parts.

In this blog post we will explore the roles of three different types of tests: unit, integration, and end-to-end in verifying the behavior of a well architected application.

Architecture

Most applications tend to have the following main parts:

  • User Interface
  • Business Logic
  • Local Database
  • Components that interface with remote services
  • Components that interface with services provided by the...

Continue reading →


Why You Should Use NSFetchedResultsController?

NSFetchedResultsController is a very useful class provided by the CoreData framework. It solves many performance issues you frequently run into while reading a large amount of data from database and displaying that data using a UITableview, UICollectionView or MKMapView. You should always use the fetched results controller unless you have a good reason not to. In this post, I would like to show you why using a fetched results controller is a good idea.

Consider an app that shows a list of news feed related to Apple products using a table view. We will call this app FeedLoader. When a row in feed table view is tapped, it shows more information about the feed in a detail view.

feed_loader_app.png

Initial Design

We can approach the design of this app in multiple ways, but the one below will provide us a good context for discussing why not using a fetched results controller might not be a good idea.

without_fetchedresultscontroller_design.png

...

Continue reading →


Creating Debug Builds on iOS

If you are like me, you tend to use the same device for testing the version of your app submitted to the App Store and the version you are currently working on. It would be great if we could install those versions separately so that we can keep using the one from the App Store uninterrupted like a real user would do. This blog post shows you a quick and easy way to let both versions co-exist as shown in figure below.

separate_icons_for_release_and_debug.png

Every iOS app has a bundle identifier that is used to uniquely identify it in the App Store. In order to have a separate entry for the debug build in iOS Springboard, we need to somehow differentiate its bundle identifier from the release build’s bundle identifier. We can achieve that by adding the value contained in BUNDLE_ID_SUFFIX user-defined build setting as a suffix. Keep reading to find out how to create a user-defined build setting. We also need to give the debug...

Continue reading →


Comparing in Swift

The whole world is obsessed with comparison. Lebron vs. Jordan, Obama vs. Putin, Viper vs. Mountain, iOS vs. Android, and the list goes on. Let’s indulge ourselves in this perverse pleasure of comparison for a bit here. Say we want to compare The Dark Knight with Man of Steel. We can start by creating a class that stores movie information.

class Movie {
    let name: String
    var tomatometer: Int

    init(name: String, tomatometer: Int = 0) {
        self.name = name
        self.tomatometer = tomatometer
    }
}

Now let’s compare.

let darkKnight = Movie(name: "Dark Knight", tomatometer: 94)
let manOfSteel = Movie(name: "Man of Steel", tomatometer: 56)

if manOfSteel < darkKnight {
    println("The Dark Knight is a better movie than Man of Steel.")
}

Swift gets angry at us when we start comparing things willy-nilly. It shows us a rather cryptic message: Cannot invoke ‘>’ with an...

Continue reading →


Understanding Interfaces

You might have heard of this design principle before: “Program to an interface, not an implementation.” Let’s understand what that really means.

Consider we are building an application that shows movie information to the user. To get things started, we will download a list of top 10 movies released in 2014 from Rotten Tomatoes and save it in a json file.

// movies.json

{ 
    "movies": [
        {
            "id": "770860165",
            "title": "Boyhood"
        },
        {
            "id": "770860166",
            "title": "The LEGO Movie"
        },

        // 8 more entries not shown here ...
    ]
}

We can easily write a class that reads the content of movies.json into memory. Let’s call it MoviesInfoFileReader.

@implementation MoviesInfoFileReader

- (NSArray *)readMoviesInfo {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [bundle
...

Continue reading →


Test-Driven Development in Swift

In this blog post, we will learn how to build a simple iOS app menu (shown below) using Test-Driven Development in Swift.
app_menu.png
Here are things you need to know to fully understand the concepts presented in this post:

  • Xcode 6
  • Familiarity with basic concepts in Swift
  • Familiarity with commonly used classes in UIKit and Foundation (e.g., UITableView and NSNotificationCenter)
  • Familiarity with XCTest. If you have never used XCTest before, please read the XCTestCase section from Matt Thompson’s blog post on the topic.

Create a new iOS project in Xcode 6. Select the Single View Application template. Use AppMenu for Product Name, Swift as the language, and iPhone for Devices. Make sure the Use Core Data check box is not selected. For this exercise we won’t be using Storyboards. So delete the Main.storyboard file. Don’t forget to remove the storyboard name (Main) from the Main Interface drop-down...

Continue reading →


Splitting a Commit in Git

In this blog post, we will learn how to split a commit in Git.

Step 1: Clone this repo on your local machine.

git clone git@github.com:pawanpoudel/split_dudeism.git

Step 2: cd into split_dudeism directory and git log it.

cd split_dudeism
git log --oneline
923c105 Go ahead, read me...
4ea45e4 Split me. I am too big...
a258b8e Are you going to a lebowski fest?
e61add7 Dudeism - this is where it all starts

Step 3: Let’s split the second commit from top into three. We will give that commit a name first.

git branch split_target 4ea45e4

Step 4: Rebase interactively with split_target‘s immediate parent as the base commit.

git rebase -i split_target~

We are using the ~ (tilde) here to get to split_target’s parent. You might have seen the ^ (caret) being used to get to a parent in other examples. There is a subtle difference between these two. I think ~ is a better choice for our...

Continue reading →