Safe Casting in Objective-C

I’m writing a small safe casting for Objective-C. I’ll be putting it on GitHub

The Story

Somewhere on the web, there was some test I took to determine how well I know Objective-C. I think it was elance. One question which infuriated me at the time was something like “if you have an array NSArray *a, how do you make it an NSMutableArray?” The reason I got angry was that the answer was supposedly

NSMutableArray *mutableArray = (NSMutableArray *)a;

Except that this is tremendously dangerous, wrong, stupid, crazy… well. You get the picture. The real answer of course is something like

NSMutableArray *mutableArray = [a mutableCopy];

Unless you want to actually modify the same instance that a is if it’s a mutable array, in which case you have to do the all-too-familiar dance

NSMutableArray *mutableArray;
if ([a isKindOfClass:[NSMutableArray class]]) {
    mutableArray = a;

At which point you proceed to mutate mutableArray, which is also a, possibly ignoring the fact that mutableArray may be nil. Or maybe you return early if it’s nil.

Casting is Dangerous

If you cast between object that are the same foundational type, no work is done. What I mean is that if you cast from ...


I’ve written Objective-C code to turn a service response into a fully hydrated model object too many times. It also seems I’m not the only one. Just a couple of weeks ago, I decided to put together OHMKit so I’d never have to write boilerplate code for object mapping again.

Check out the source on GitHub!

OHMKit is a mixin to make any Objective-C class easier to hydrate from a dictionary representation, such as you might get from a web service. It makes it easy to keep any direct knowledge of the idiosyncrasies of the service you’re consuming tucked away in a single place.

It exists because RestKit (which is awesome by the way), is sometimes too big, heavy, and indirect.

This project doesn’t know about networks. Use AFNetworking.

This project doesn’t know about routes. Use SOCKit.

This project doesn’t know about CoreData. It will not manage graphs of entities for you quite like RestKit does. But it is built on KVO, and does not care about your model objects’ super class. So you can safely make subclasses of NSManagedObject mappable.


Basic Mapping

Given a model

@interface MYModel : NSObject
@property (nonatomic, strong ...

Per File ARC in CocoaPods

tl;dr do |s| = 'MyPod'
  non_arc_files = 'Classes/FirstNonARCClass.m',
  s.requires_arc = true
  s.source_files = 'Classes/*.{h,m}'
  s.exclude_files = non_arc_files
  s.subspec 'no-arc' do |sna|
    sna.requires_arc = false
    sna.source_files = non_arc_files


Automatic reference counting (ARC) is a good thing. It's a great compile-time technology that makes it easier, in most cases, to not accidentally introduce trivial memory leaks in modern Objective-C apps.

But sometimes, you have older code with traditional memory management; it's not really worth converting to ARC if it's correct, and possibly finely tuned. And sometimes ARC introduces a little unnecessary overhead that can balloon out of control when handling large numbers of objects. There are also good reasons to put Objective-C objects into structs or other odd places that ARC prohibits or makes difficult (Objective-C++ anyone?).

That said, ARC is almost always a good idea. And so disabling ARC should be the exception, not the rule.


CocoaPods is an excellent dependency management system for Objective-C projects. Dependencies are distributed as 'Pods' which are described in podpecs. A podspec is a kind of build description, that specifies where the source ...

CocoaPods and GYP


CocoaPods is an excellent dependency management system for Objective-C projects. Dependencies are distributed as 'Pods’ which are almost exactly like gems. A podspec is a kind of build description, that specifies where the source is to be found, dependencies it has, and how it should be configured and compiled. The best part is that they’re extremely legible.

This is a great improvement over the typical git submodule, or linked Xcode project for each dependency. To use CocoaPods, you specify your application’s dependencies in a Podfile. This is typically a concise list of the pods required to build the application. CocoaPods generates a Pods project with a single target consisting of a single static library custom-built for your app to contain all the dependencies in one place. The Pods project that gets put into a workspace along with your project, so that everything plays nice with Xcode as both and IDE and as a build system. The Pods project doesn’t get checked in to your repository because it can be completely regenerated from your Podfile.

CocoaPods turns out to be a partial build system that takes some of the bite out of Xcode. With respect to dependencies ...

What if the MagSafe2 Adapter was the new iPhone Adapter?

I will go ahead and claim total ignorance on this. But why does a MagSafe adapter have 5 pins? Is it possible that data might be sent over those extra pins?

Maybe Apple wanted to make MagSafe thinner in order to make their new retina laptop thinner. But the original MagSafe is barely thinner than USB. So I thought that, just maybe, the new MagSafe connector that’s coming with my Retina MacBook Pro next week might just fit my next iPhone.

Work + World Cup

It turns out the my project to Duplicate Windows that I developed for academic purposes has an excellent use for watching the World Cup, or any other web video, while working. Just shrink down the browser window to the size of the video, and duplicate it. Set the Duplicate Window to always sit on top, shrink it down to whatever size accommodates your working environment, and you’re ready to go.

This gets around two major problems with flash web video; you can now resize the video, and you can keep the window above other windows. Use it for your keeping an eye on your favorite sporting event or for the next Apple Keynote. So go download it! It's free!


This is just to say that SizeUp is a piece of software that I use constantly to manage my windows on the Mac. It’s a lot like a tiling window manager, and I find it’s the best method of spatially organizing windows. I’m writing this here because I’ve never seen anybody else using it, and I can no longer imagine working without it. With just a few keystrokes, you can resize and reposition windows to a wide variety of customizable shapes and positions. It’s free to try and I strongly recommend it to anyone who ever juggles more than one window at a time.

It’s particularly geared towards a keyboard-centric control of window management, but the same developer has made a mouse-based window manager (Cinch) that might be better suited for some.

Custom Keyboard Shortcuts to Dynamic Menu Items

Here, I outline a method for adding a keyboard shortcut to menu items with dynamic names in Mac OS X. Custom keyboard shortcuts on the Mac are generally great, and you can create your own system-wide, or application-specific shortcuts in the keyboard preference pane. All you need to do is provide the precise name of the menu item you want to make a shortcut to. Instructions for how to do this can be found at lifehacker. But it's a problem if the menu item changes dynamically.

I’ve been using Versions as a svn client for a couple of weeks to help manage my writing, and so far it’s proven to be a great app. But in managing LaTeX projects, there are a lot of files that should to be ignored by the repository. Unfortunately, Versions doesn’t have a keyboard shortcut for ignoring a selected file. To make matters worse, the name of the menu item changes to reflect the selected file, so making a keyboard shortcut in the usual way doesn’t work.

I guess this wouldn’t be so bad if I weren’t a keyboard junkie. But anyway, here’s how I worked around ...

Duplicate Windows in Mac OS X

Allow me to introduce a project I’ve had lying around for some months that I’ve found extremely useful thus far: Duplicate Windows. It allows you to create a visual copy of any window on Mac OS X, and keep the new window updated on-the-fly.

The program came about when I was teaching a statistics lab twice a week in Fall 2009. The first portion of every lab, I performed various sorts of demonstrations using the statistical software, R. As is usual in such cases, I stood up front facing the class, with the projection screen behind me. The perfect scenario to mirror the display on my laptop and the projector.

But then, I wanted to have some personal notes in-front of me to present the material in the way I had carefully prepared, and I also wanted to have a small bank of pre-typed commands to copy and paste into the R console to speed up the lecture portion of the lab. I didn’t want these resources projected in-front of the entire class… the perfect scenario to set my laptop in extended desktop mode.

One morning, I decided I needed the best of both worlds. I wrote ...

Reclaim Your Mac’s Playback Control Keys

tl;dr: Run Quicktime to prevent iTunes from launching every time you use built-in keyboard controls or the Apple remote

Don’t let iTunes hijack your keyboard’s built-in playback-control keys. A lot of programs take advantage of the Apple remote, or laptops’ built-in track control buttons to let you control their playback without switching back to that app. Personally, I use Cog to play music I keep as flac.

But after upgrading to Snow Leopard, iTunes has decided to hijack those controls a bit. The buttons still control Cog, but iTunes launches whenever you press any of them. Today, I happened upon a solution: keep Quicktime Player running in the background.

What I find upsetting about this whole issue is that Apple clearly recognized that iTunes shouldn’t launch every time one of those keys is pressed. So they made Quicktime, and probably Front Row override the default behavior. But as far as I can tell, they didn’t tell anyone else how to do it.

Mac Screenshot Commands Cheat Sheet

I’m always forgetting exactly how to take screenshots on my Mac. The Shift, Command, Control, 3s and 4s all get garbled up in my head. So for my own benefit, and perhaps your own I’ve consolidated them here into a convenient list.

Command-Shift-3 :: Take a screenshot of the whole screen.
Command-Shift-4 :: Take a screenshot of an area you select.
Command-Shift-4-Space :: Take a screenshot of a window.

All these commands save a file to your Desktop. Adding the ‘Control’ key to any of them puts the image in your clipboard instead.

Additionally, you can take, or initiate screenshots from the command line using the very rich built-in screencapture command.

    usage: screencapture [-icMPmwsWxSCUto] [files]
      -c         force screen capture to go to the clipboard
      -C         capture the cursor as well as the screen. only in non-interactive modes
      -d         display errors to the user graphically
      -i         capture screen interactively, by selection or window
                   control key - causes screen shot to go to clipboard
                   space key   - toggle between mouse selection and
                                 window selection modes
                   escape key  - cancels interactive screen shot
      -m         only capture the main monitor, undefined if -i is set
      -M         screen capture output will go to a new Mail message
      -o         in ...

Detecting Displays

In the process of making Mirror Displays I learned more or less what Quartz Display Services in Mac OS X has to offer. It more or less lets to get and set all size, position, color, gamma, mirroring settings for attached monitors. It lets you fade the monitors in and out, and lets your app monopolize output to any monitors. An important element to the Display Services though, is that you can register to be notified of any changes to the displays.

I’m writing this particular post because I know that Java has some problems when it comes to dynamically detecting multiple monitors when you go and connect and disconnect them. Though I certainly hope Sun eventually fixes the problem, this sounded like the sort of thing that unfortunately needs to be solved on the native platform. I haven’t done any programming in Windows or Linux in a long time, but I hope I can help those using Mac OS X by showing you a barebones program that just sits and listens for display changes. I’m not going to make it talk to Java, but you make a little client-server setup, or maybe you could use the ...