Skip to content

Instantly share code, notes, and snippets.

@edom18
Created March 17, 2014 14:51
Show Gist options
  • Save edom18/9600705 to your computer and use it in GitHub Desktop.
Save edom18/9600705 to your computer and use it in GitHub Desktop.
[Objective-C] Swizzling(ランタイムAPI)を使ってDebugをしやすくする ref: http://qiita.com/edo_m18/items/9c57f4714d5c14a990c4
@interface NSString (sample)
- (NSString *)swapLowercaseString;
@end
////////////////////////////////////////
@implementation NSString (sample)
- (NSString *)swapLowercaseString
{
NSString *lowercase = [self swapLowercaseString];
NSLog(@"Called. %@", lowercase);
return lowercase;
}
@end
NSString *sample1 = @"This is Sample";
NSString *sample2 = [sample1 lowercaseString]; // => "Called. this is sample"
NSLog(@"%@", sample2); // => "this is sample"
#import <objc/runtime.h>
#import "NSString+sample.h"
int main(int argc, char * argv[])
{
// NSString#lowercaseStringの実装を取り出す
Method lowercaseString = class_getInstanceMethod([NSString class], @selector(lowercaseString));
// カテゴリで追加した`swapLowercaseString`の実装を取り出す
Method swapLowercaseString = class_getInstanceMethod([NSString class], @selector(swapLowercaseString));
// 取り出した実装を入れ替える
method_exchangeImplementations(lowercaseString, swapLowercaseString);
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([SampleAppDelegate class]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment