Skip to content

Instantly share code, notes, and snippets.

@staxmanade
Created February 12, 2015 17:01
Show Gist options
  • Save staxmanade/6f462e1829a9976783c0 to your computer and use it in GitHub Desktop.
Save staxmanade/6f462e1829a9976783c0 to your computer and use it in GitHub Desktop.
Fail Fast and assert when [UIImage imageNamed:name] cannot load an image
//
// UIImage+FailFast.h
//
// Created by Jason Jarrett on 2/11/15.
// Copyright (c) 2015 Jason Jarrett. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (FailFast)
@end
//
// UIImage+FailFast.m
//
// Created by Jason Jarrett on 2/11/15.
// Copyright (c) 2015 Jason Jarrett. All rights reserved.
//
// Let's only use this in a DEBUG/developer mode
#if DEBUG
#import "UIImage+FailFast.h"
#import "objc/runtime.h"
static Method origImageNamedMethod = nil;
static NSArray *imagesAllowedToBeMissing;
@implementation UIImage (FailFast)
+ (void)load {
// Swizzle the core [UIImage imageNamed:name] selector with our custom selector
origImageNamedMethod = class_getClassMethod (self, @selector (imageNamed:));
method_exchangeImplementations (origImageNamedMethod, class_getClassMethod (self, @selector (assertIfImageNamedNotFound:)));
static dispatch_once_t onceToken;
dispatch_once (&onceToken, ^{
// Setup a colleciton of images that may be missing but are allowed to be nil
imagesAllowedToBeMissing = @[
// TODO: if any images are OK missing - add them here
// @"",
];
});
}
+ (UIImage *)assertIfImageNamedNotFound:(NSString *)name {
NSLog (@"Loading image named: %@", name);
// This will call the original core imageNamed selector which actually loads the image
UIImage *image = [self assertIfImageNamedNotFound:name];
if ([imagesAllowedToBeMissing indexOfObject:name] == NSNotFound) {
NSAssert (image != nil, @"Failed to load imageNamed: %@", name);
}
return image;
}
@end
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment