OC高效率52之「方法調配技術」調試「黑盒方法」

#import "ViewController.h"
#import <objc/runtime.h>
#import "NSString+EocMyAdditions.h"
@interface ViewController ()

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //類的方法列表會把選擇子的名稱映射到相關的方法實現之上,使得「動態消息派發系統」可以據此找到應該調用的方法。這些方法均以函數指針的形式來表示,這種指針叫IMP
    id(*IMP)(id,SEL);
    //1.如何互換兩個方法的實現
    Method originaMethod = class_getInstanceMethod([NSString class], @selector(lowercaseString));
    Method swappedMethod = class_getInstanceMethod([NSString class], @selector(eoc_myLowercaseString));
    
    method_exchangeImplementations(originaMethod, swappedMethod);//方法的實現進行交換  就能夠進行黑盒的調試
    
    NSString *string = @"ThIs is tHe StriNg";

    NSString *lowercaseString = [string lowercaseString];
    
    NSLog(@"%@",lowercaseString);
    //this is the string
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
#import <Foundation/Foundation.h>

@interface NSString (EocMyAdditions)

-(NSString *)eoc_myLowercaseString;
@end

#import "NSString+EocMyAdditions.h"

@implementation NSString (EocMyAdditions)

-(NSString *)eoc_myLowercaseString
{
    NSString *lowercase = [self eoc_myLowercaseString];//用此方法跟lowercaseString互換,不會陷入遞歸的死循環
    NSLog(@"分類中打印》》》》》》》》%@ =>%@",self,lowercase);////分類中打印》》》》》》》》ThIs is tHe StriNg =>this is the string
    return lowercase;
}


@end
相關文章
相關標籤/搜索