iOS 4 & 5 incompatibility in dismissing a modal view

22 Mar 2012

Here is one annoying problem.

In iOS 4, when I want to dismiss a modal view, I would:

[self.parentViewController dismissModalViewControllerAnimated:YES];

But that doesn't work on iOS 5 anymore.

On iOS 5, I have to use `self.presentingViewController` instead, but iOS 4 does not support the property.

So, what do we do now?

Ruby-ish Hacking

I have decided to build a hook, which is an Objective-C category with 2 fake properties, namely `presentingViewControllerand ``presentedViewController```.

Moreover, I chain the method `presentModalViewController:animated:and ``dismissModalViewControllerAnimated:``` in order to set/unset those properties.

The techniques used are Fake Instance in Category and Method Swizzling.

By the way, these types of technique are so common in Ruby.

Walla! iOS 4 magically supports `self.presentingViewController`. You really don't need to do anything but including 2 files into your project. The files are:

You may grab the source code at UIViewController+PresentingViewController.

Give it a kudos