zoukankan      html  css  js  c++  java
  • 运行时Runtime演示方法交换

    1、按钮分类

    • 演示给整个工程中的按钮添加点击音效。
    • 写一个分类,重写类的 load方法。
    #import "UIButton+CH.h"
    
    #import <objc/runtime.h>
    
    @implementation UIButton (CH)
    
    + (void)load {
    	[super load];
    
    	// 这个是系统原有的方法
    	Method oldObjectAtIndex = class_getInstanceMethod([UIButton class], @selector(sendAction:to:forEvent:));
    	// 自定义的方法
    	Method newObjectAtIndex = class_getInstanceMethod([UIButton class], @selector(custom_sendAction:to:forEvent:));
    	// 交换方法
    	method_exchangeImplementations(oldObjectAtIndex, newObjectAtIndex);
    }
    
    - (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    	// 可条件选择走系统方法
    	[self custom_sendAction:action to:target forEvent:event];
    
    	[CHTool playSoundEffect:@"music3" withType:VoiceTypeIsMp3];
    
    	CHLog(@"捕捉所有按钮事件");
    }
    
    @end
    
    • 要使在整个工程中生效,将该分类的头文件添加到工程的Pch文件即可。

    2、记录NSMutableArray添加的每一个对象

    #import  <objc/runtime.h>
    
    @implementation NSMutableArray (LoggingAddObject)
    
    + (void)load {
    	Method addobject    = class_getInstanceMethod(self, @selector(addObject:));
    	Method logAddobject = class_getInstanceMethod(self, @selector(logAddObject:));
    	method_exchangeImplementations(addObject, logAddObject);
    }
    
    - (void)logAddObject:(id)aobject {
    	[self logAddObject:aObject];
    	NSLog(@"Added object %@ to array %@", aObject, self);
    }
    @end
    
    • 要使在整个工程中生效,将该分类的头文件添加到工程的Pch文件即可。
  • 相关阅读:
    微软的权限框架Asp.Net Identity
    排序算法
    在线编辑器
    It's only too late if you decide it is. Get busy living, or get busy dying(转)
    一个程序员的四年经历反思(转)
    wamp的安装使用(转)
    JDBC连接数据库经验技巧(转)
    重写ResultSet实现分页功能(最好的分页技术)(转)
    import android.provider.Telephony cannot be resolved
    linux-多线程
  • 原文地址:https://www.cnblogs.com/CH520/p/13794728.html
Copyright © 2011-2022 走看看