Search code examples
iosparse-platformuiimageviewsdwebimageobjective-c-category

Apply category to a framework class


What I want to achieve is to enable the PFImageView class (from Parse framework) respond to SDWebImage methods. SDWebImageis a framework in itself, but since it essentially applies a category to UIImageView - and PFImageView inherits from UIImageView - it seems that it should be possible to achieve this.

I tried creating a separate category PFImageView+SDWebImage, where in the .h file I simply added

#import <SDWebImage/UIImageView+WebCache.h>

but this is clearly not enough as I still receive an crash with an error saying [PFImageView setImageWithURL:placeholderImage:completed:]: unrecognized selector sent to instance.

How does one achieve what I'm trying to do here correctly?


Solution

  • A category properly applied to UIImageView will automatically be available to subclasses. You don't need to do anything special. And your header shouldn't matter at all. Headers don't apply categories; they just tell the compiler that they exist so you won't receive warnings. Categories are applied when the relevant implementations are loaded (specifically they happen when the +load method is called, but in the iOS world you can think of this as "when the program starts.")

    All that suggests that you're just not loading your category code at all. That's a very common problem. Make sure that you're compiling the relevant .m file that implements this category, and make sure that if you're linking this from a static library, that you're using the -ObjC flag. See QA1490 for full details. The short version is that if you put category code in a static library, the linker may see it as unused and strip it. The -ObjC flag tells the compiler that this is the crazy awesome dynamic ObjC world and sometimes things that don't look like they're used actually are.