Skip to content

Instantly share code, notes, and snippets.

@cbowns
Created May 7, 2012 04:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbowns/2625835 to your computer and use it in GitHub Desktop.
Save cbowns/2625835 to your computer and use it in GitHub Desktop.
A nil-checking [UIImage imageNamed:] category. Uses thrown and caught exceptions to break into the debugger if you have exception breakpoints turned on. Use #define UIIMAGE_IMAGENAMED_NILCHECK 0 to turn off the throw-and-catch.
//
// UIImage+MPImageNamedNilCheck.h
//
// Created by Christopher Bowns on 5/6/12.
// Copyright (c) 2012 Mechanical Pants Software. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (MPImageNamedNilCheck)
// Throws and catches an exception when [UIImage imageNamed:name] returns nil.
// Turn on exception breakpoints to halt execution when this happens.
// Use #define UIIMAGE_IMAGENAMED_NILCHECK 0 to avoid throwing and catching exceptions.
+ (UIImage *)imageNamedWithNilCheck:(NSString *)name;// load from main bundle with a nil check.
@end
//
// UIImage+MPImageNamedNilCheck.m
//
// Created by Christopher Bowns on 5/6/12.
// Copyright (c) 2012 Mechanical Pants Software. All rights reserved.
//
#import "UIImage+MPImageNamedNilCheck.h"
@implementation UIImage (MPImageNamedNilCheck)
+ (UIImage *)imageNamedWithNilCheck:(NSString *)name;// load from main bundle with a nil check.
{
UIImage *image = [UIImage imageNamed:name];
@try {
if (image == nil) {
NSLog(@"%s nil image returned from [UIImage imageNamed:@\"%@\"]", __func__, name);
#if UIIMAGE_IMAGENAMED_NILCHECK
[NSException raise:@"Nil image returned from +imageNamed:" format:@"Image named “%@” was not found.", name];
#endif
}
}
@catch (NSException *exception) {
// Good work.
}
return image;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment