Tuesday, 31 July 2012

Could Not Instantiate Class Named 'NSLayoutConstraint'

Back into iPhone development again, I found myself briefly scratching my head at an app crashing when testing on one of my real devices, but not another. The console shows a stack trace with the pertinent complaint being


*** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named NSLayoutConstraint'*** 

Well that's no good now is it ? I found that it runs just fine on my iPhone running iOS 6 beta 3, but crashes out with the above error when running on my iPod 5.1. It turns out that the new Xcode has introduced some new functionality into the Interface Builder, some of which is enabled by default when creating new XIBs.

The offending item is this case, is the use of "Autolayout" of interfaces. It seems that when using Xcode to create new interfaces, Autolayout is checked by default, even though it is a feature available for iOS 6 onwards. My project targets iOS 4, so I was a bit surprised to see it assume such a breaking setting, but maybe that is just because the Xcode version I am using is also still in beta (Version 4.5 4g125j).

The fix is quite simple, Select the XIB which is failing to load, and from the panes down the right, find the one entitled "Interface Builder Document". Under here, are settings for deployment versions (which represents the minimum version you want to support), which can be changed to match your expectations.





Selecting the correct version will result in the build failing, quoting a build error such that:

Auto Layout on iOS Versions prior to 6.0

Underneath this setting, is a checkbox entitled "Use Autolayout" which should be unchecked, as per the build error. Rinse and repeat for any other XIBs you have created using Xcode 4.5.