Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active March 9, 2017 08:26
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save steipete/e27db036126f9261092e to your computer and use it in GitHub Desktop.
Save steipete/e27db036126f9261092e to your computer and use it in GitHub Desktop.
Retrofitting containsString: on iOS 7
#import <Foundation/Foundation.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000
@interface NSString (PSPDFModernizer)
// Added in iOS 8, retrofitted for iOS 7
- (BOOL)containsString:(NSString *)aString;
@end
#endif
// PSPDFModernizer.m
#import "PSPDFModernizer.h"
#import <objc/runtime.h>
#if __IPHONE_OS_VERSION_MIN_REQUIRED < 80000
@implementation NSString (PSPDFModernizerCreator)
+ (void)load {
@autoreleasepool {
[self pspdf_modernizeSelector:NSSelectorFromString(@"containsString:") withSelector:@selector(pspdf_containsString:)];
}
}
+ (void)pspdf_modernizeSelector:(SEL)originalSelector withSelector:(SEL)newSelector {
if (![NSString instancesRespondToSelector:originalSelector]) {
Method newMethod = class_getInstanceMethod(self, newSelector);
class_addMethod(self, originalSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
}
}
// containsString: has been added in iOS 8. We dynamically add this if we run on iOS 7.
- (BOOL)pspdf_containsString:(NSString *)aString {
return [self rangeOfString:aString].location != NSNotFound;
}
@end
#endif
@dflems
Copy link

dflems commented Jul 21, 2014

Since you need to add PSPDFFileLoaderHook anyway just to make this work, what's the benefit of doing this in an __attribute__((constructor)) function vs. doing it in the + load method of that class?

@steipete
Copy link
Author

@dflems You're right, this is nicer in a category. (Got the same feedback from @danieleggert)

@ReneLindhorst
Copy link

@steipete You might want to update your blog post to reflect the changes ;-)

@patoroco
Copy link

I also remove warnings from compiling because method is not implemented:

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wincomplete-implementation"
@implementation NSString (ContainsString)
#pragma GCC diagnostic pop
...
@end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment