iosobjective-cuiimageobjective-c-categoryimagenamed

Override UIImage imageNamed - what are my options?


Basically my code heavily uses [UIImage imageNamed] which by default fetches image from app bundle.

Now I want the images to be returned from a directory deep within Documents (or library or whatever) - instead of main bundle. And since there are so many instances of imageNamed calls, I am considering to extend (read replace) UIImage ImageNamed implementation for this purpose.

I already went through this but can't quite make up what should I do, and what is best:

  1. Make a category of UIImage
  2. Create a subclass of UIImage
  3. Method swizzling

I also do not know if I have to take care of @2x images. My current bundle includes bunch of them, and I suppose my implementation will also have to take care of it. But not sure how.


Solution

  • The cleanest, most elegant and easiest to maintain long term solution is to use a category on UIImage. Define a custom method on UIImage, and then use a Find & Replace to replace all your imageNamed calls to your new method.

    Don't use swizzling (it will introduce weird, undocumented bugs) and is very difficult to maintain or debug. (Also, if you swizzle, it will break in places where you do want to use the default implementation of imageNamed).

    There's no need to subclass UIImage for what you're trying to do because you don't need an instance method.