Skip to content

Instantly share code, notes, and snippets.

@asmallteapot
Created October 7, 2015 17:52
Show Gist options
  • Save asmallteapot/35dcf38971edc85df6da to your computer and use it in GitHub Desktop.
Save asmallteapot/35dcf38971edc85df6da to your computer and use it in GitHub Desktop.
Function for asserting that a code path isn’t called from a subclass of a given class.
void ASTAssertNotCalledFromSubclassOfClass(Class doNotCallFromThisClass) {
NSString *bundleName = [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleNameKey];
for (NSString *symbol in [NSThread callStackSymbols]) {
if ([symbol containsString:bundleName]) {
NSRange openBracketRange = [symbol rangeOfString:@"["];
if (openBracketRange.location != NSNotFound) {
NSRange searchRange = NSMakeRange(openBracketRange.location, (symbol.length - openBracketRange.location));
NSRange nextSpaceRange = [symbol rangeOfString:@" " options:0 range:searchRange];
if (nextSpaceRange.location == NSNotFound) {
// well, this shouldn't happen…
continue;
}
NSUInteger classNameLocation = (openBracketRange.location + 1);
NSUInteger classNameLength = nextSpaceRange.location - classNameLocation;
NSRange classNameRange = NSMakeRange(classNameLocation, classNameLength);
NSString *className = [symbol substringWithRange:classNameRange];
Class aClass = NSClassFromString(className);
if (aClass) {
if ([aClass isSubclassOfClass:doNotCallFromThisClass]) {
NSAssert(NO, @"No, seriously, do not call this method from %@", NSStringFromClass(doNotCallFromThisClass));
continue;
}
}
}
}
}
}
@implementation AppDelegate
- (UIViewController *)viewControllerForAwfulHacks {
// YOU ALREADY HAVE A VIEW CONTROLLER, JUST USE THAT
ASTAssertNotCalledFromSubclassOfClass([UIViewController class]);
return self.window.rootViewController;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment