Last Updated: February 25, 2016
·
992
· lucabernardi

How to avoid to hardcode the nib name

On iOS when it's time to load some kind of resource such as images, nib, etc… you have to hard code the resource name.

This "magic string" are problematic in two situation:

  1. When you write it for the first time 'cause you don't have any sort of autocompletion. (It happened to me several times that I can't figure out why an image doesn't show up only to discover that I've typed the wrong name)
  2. When you refactor your code. This is especially true, in my case, for the nib.

Regarding the first issue somethings is happening in the community: Patrick Hughes has put together a [python script](http://www.cimgf.com/2013/01/29/down-with-magic-strings/( that generates a #define for every image in the project and the rgen project that try to mimic the Android's R resource class behavior.

The second issue create me several headache especially with nib files. I consider myself a refactor guy, I love to improve my code and the Xcode's Refactor feature is my best friend.

The problems starts when you have some + [UINib nibWithNibName: bundle:] or - [UIViewController initWithNibName: bundle:] with the nib name hardcoded as a NSString and you change the name of the controller class or the view class and the refactor also automatically change the nib name.

So I use this little trick to let Xcode refactor the nib name around my code, instead of hardcode the nib name as a string I write something like this:

UINib *cellNib = [UINib nibWithNibName: NSStringFromClass([LBDocumentViewCell class])
                               bundle: nil];

This ensure that when Xcode refactor my code it also will take care of changing this name.