Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile time check for valid file references in Xcode

Is it possible to force the Xcode complier to verify that files referenced in code are valid?

There are multiple points in Cocoa development when you naturally reference a file programmatically via an NSString:

[UINib nibWithNibName:@"MyNib" bundle:nil];
[UIImage imageNamed:@"MyImage"];
[[UIViewController alloc] initWithNibName:@"MyNib" bundle:nil];

Is there any way at compile time to check is these file references are valid?

Often times after using above methods, I end up changing the name of the referenced file but forget to change the name in code. Everything complies without a problem and it is only when you happen to go to the portion of the app that accesses this file that the bug will reveal itself.

Is there another approach or technique that people use to avoid this sort of error?
Referencing a file name via a string feels very fragile.

like image 984
bearMountain Avatar asked Jan 04 '13 18:01

bearMountain


1 Answers

Warning: This answer is mostly outdated. The general idea is fine but better solutions exist now (e.g. Image assets with a SwiftGen script to generate an enum).

Nibs usually have a class with the same name as the file, e.g.

[[MyViewController alloc] initWithNibName:NSStringFromClassName([MyViewController class]) bundle:nil];

I usually hide it into the controller's init method as [self class].

For image loading, compile-time checks are difficult. Help yourself with macros, first replace the loading method by a simple macro, e.g.

#define LOAD_IMAGE(__IMAGE_NAME__) [UIImage imageNamed:__IMAGE_NAME__]

First thing you should do is to put an assert into this macro and always check that the image was successfully loaded. It's not a compile-time check but it helps to find missing resources.

The second thing is to write a ruby/python/shell/(any scripting language) script that will search your source files for LOAD_IMAGE and check if the file (between parenthesis) exists. As a shell script, it will be very simple (e.g. using grep). You can add this script into your xcode project to be run when compiling. Don't forget to check images referenced by xibs.

However, often you have to create the image name dynamically, e.g. NSString* imageName = [NSString stringWithFormat:@"image_%i", index]. There's no way how you can check this at compile time.

Also don't forget to do the reverse check - don't include image files which are not used anywhere.

like image 188
Sulthan Avatar answered Sep 18 '22 04:09

Sulthan