1. 给NSObject类动态添加属性
h定义部分

[cpp] 
@interface UIWebView (LoadProgress) 
 
@property (nonatomic, assign) NSInteger resourceCount; 
 
@end

@interface UIWebView (LoadProgress)

@property (nonatomic, assign) NSInteger resourceCount;

@end

m实现部分

首先要定义一个全局的key

[cpp] 
// resourceCount object keys  
static void *s_resourceCountKey = &s_resourceCountKey; 
//static void *s_resourceCountKey = "s_resourceCountKey";

// resourceCount object keys
static void *s_resourceCountKey = &s_resourceCountKey;
//static void *s_resourceCountKey = "s_resourceCountKey";
初始

[cpp]
@implementation UIWebView (LoadProgress) 
@dynamic resourceCount;

@implementation UIWebView (LoadProgress)
@dynamic resourceCount;
实现
[cpp]
#pragma mark Accessors and mutators  
 
- (NSInteger)resourceCount 

    NSNumber *resourceCountNumber = objc_getAssociatedObject(self, s_resourceCountKey); 
    if (! resourceCountNumber) 
    { 
        return 0; 
    } 
    else 
    { 
        return [resourceCountNumber integerValue]; 
    } 

 
- (void)setResourceCount:(NSInteger)rCount 

    objc_setAssociatedObject(self, s_resourceCountKey, [NSNumber numberWithInteger:rCount], OBJC_ASSOCIATION_RETAIN_NONATOMIC); 
}

#pragma mark Accessors and mutators

- (NSInteger)resourceCount
{
    NSNumber *resourceCountNumber = objc_getAssociatedObject(self, s_resourceCountKey);
    if (! resourceCountNumber)
    {
        return 0;
    }
    else
    {
        return [resourceCountNumber integerValue];
    }
}

- (void)setResourceCount:(NSInteger)rCount
{
    objc_setAssociatedObject(self, s_resourceCountKey, [NSNumber numberWithInteger:rCount], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

这样就可以直接使用了

webView.resourceCount = 10;

2. 给NSObject类动态添加代理protocol
同属性

动态创建代理暂时先不写了

3. 替换或变更NSObject类方法Method
基本替换方法

[cpp]
// 替换类方法  
// frome: CoconutKit  
IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation) 

    // Get the original implementation we are replacing  
    Class metaClass = objc_getMetaClass(class_getName(clazz)); 
    Method method = class_getClassMethod(metaClass, selector); 
    IMP origImp = method_getImplementation(method); 
    if (! origImp) { 
        return NULL; 
    } 
     
    class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method)); 
    return origImp; 

 
// 替换实例方法  
IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation) 

    // Get the original implementation we are replacing  
    Method method = class_getInstanceMethod(clazz, selector); 
    IMP origImp = method_getImplementation(method); 
    if (! origImp) { 
        return NULL; 
    } 
     
    class_replaceMethod(clazz, selector, newImplementation, method_getTypeEncoding(method)); 
    return origImp; 
}

// 替换类方法
// frome: CoconutKit
IMP HLSSwizzleClassSelector(Class clazz, SEL selector, IMP newImplementation)
{
    // Get the original implementation we are replacing
    Class metaClass = objc_getMetaClass(class_getName(clazz));
    Method method = class_getClassMethod(metaClass, selector);
    IMP origImp = method_getImplementation(method);
    if (! origImp) {
        return NULL;
    }
   
    class_replaceMethod(metaClass, selector, newImplementation, method_getTypeEncoding(method));
    return origImp;
}

// 替换实例方法
IMP HLSSwizzleSelector(Class clazz, SEL selector, IMP newImplementation)
{
    // Get the original implementation we are replacing
    Method method = class_getInstanceMethod(clazz, selector);
    IMP origImp = method_getImplementation(method);
    if (! origImp) {
        return NULL;
    }
   
    class_replaceMethod(clazz, selector, newImplementation, method_getTypeEncoding(method));
    return origImp;
}

新方法定义

[cpp]
// Original implementation of the methods we swizzle  
static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL; 
 
// Swizzled method implementations  
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource);

// Original implementation of the methods we swizzle
static id (*s_UIWebView__identifierForInitialRequest_Imp)(id, SEL, id, id, id) = NULL;

// Swizzled method implementations
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource);
方法初始化需要写在类方法+ (void)load中

[cpp] 
+ (void)load 

    s_UIWebView__identifierForInitialRequest_Imp = (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(self, @selector(webView:identifierForInitialRequest:fromDataSource:), (IMP)swizzled_UIWebView__identifierForInitialRequest_Imp); 
}

+ (void)load
{
    s_UIWebView__identifierForInitialRequest_Imp = (id (*)(id, SEL, id, id, id))HLSSwizzleSelector(self, @selector(webView:identifierForInitialRequest:fromDataSource:), (IMP)swizzled_UIWebView__identifierForInitialRequest_Imp);
}
实现部分

[cpp] 
#pragma mark Swizzled method implementations  
 
static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource) 

    // 调用原方法  
    (*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView, initialRequest, dataSource); 
     
    [self setResourceCount:self.resourceCount+1]; 
     
    return [NSNumber numberWithInteger:self.resourceCount]; 
}

#pragma mark Swizzled method implementations

static id swizzled_UIWebView__identifierForInitialRequest_Imp(UIWebView *self, SEL _cmd, id webView, id initialRequest, id dataSource)
{
    // 调用原方法
    (*s_UIWebView__identifierForInitialRequest_Imp)(self, _cmd, webView, initialRequest, dataSource);
   
    [self setResourceCount:self.resourceCount+1];
   
    return [NSNumber numberWithInteger:self.resourceCount];
}

4. 代理方法检索
可直接定义到NSObject的Category中
[cpp]
// [self implementsProtocol:@protocol(UIActionSheetDelegate)]

// [self implementsProtocol:@protocol(UIActionSheetDelegate)][cpp] view plaincopyprint?
// frome: CoconutKit  
- (BOOL)implementsProtocol:(Protocol *)protocol 

    // Only interested in optional methods. Required methods are checked at compilation time  
    unsigned int numberOfMethods = 0; 
    struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO /* optional only */, YES, &numberOfMethods); 
    for (unsigned int i = 0; i < numberOfMethods; ++i) { 
        struct objc_method_description methodDescription = methodDescriptions[i]; 
        SEL selector = methodDescription.name; 
        if (! class_getInstanceMethod([self class], selector)) { 
            NSString *selectorString = [NSString stringWithCString:sel_getName(selector) encoding:NSUTF8StringEncoding]; 
            NSString *protocolName = [NSString stringWithCString:protocol_getName(protocol) encoding:NSUTF8StringEncoding]; 
            HLSLoggerInfo(@"Class %@ does not implement method %@ of protocol %@", [self className], selectorString, protocolName); 
            selectorString = nil;               // Just to remove unused variable warnings  
            protocolName = nil; 
            return NO; 
        } 
    } 
     
    return YES; 
}

// frome: CoconutKit
- (BOOL)implementsProtocol:(Protocol *)protocol
{
    // Only interested in optional methods. Required methods are checked at compilation time
    unsigned int numberOfMethods = 0;
    struct objc_method_description *methodDescriptions = protocol_copyMethodDescriptionList(protocol, NO /* optional only */, YES, &numberOfMethods);
    for (unsigned int i = 0; i < numberOfMethods; ++i) {
        struct objc_method_description methodDescription = methodDescriptions[i];
        SEL selector = methodDescription.name;
        if (! class_getInstanceMethod([self class], selector)) {
            NSString *selectorString = [NSString stringWithCString:sel_getName(selector) encoding:NSUTF8StringEncoding];
            NSString *protocolName = [NSString stringWithCString:protocol_getName(protocol) encoding:NSUTF8StringEncoding];
            HLSLoggerInfo(@"Class %@ does not implement method %@ of protocol %@", [self className], selectorString, protocolName);
            selectorString = nil;               // Just to remove unused variable warnings
            protocolName = nil;
            return NO;
        }
    }
   
    return YES;
}

http://www.2cto.com/kf/201304/204393.html

objc_runtime使用方法的几个简单例子(转)的更多相关文章

  1. extern外部方法使用C#简单例子

    外部方法使用C#简单例子 1.增加引用using System.Runtime.InteropServices; 2.声明和实现的连接[DllImport("kernel32", ...

  2. Hibernate4.2.4入门(一)——环境搭建和简单例子

    一.前言 发下牢骚,这段时间要做项目,又要学框架,搞得都没时间写笔记,但是觉得这知识学过还是要记录下.进入主题了 1.1.Hibernate简介 什么是Hibernate?Hibernate有什么用? ...

  3. AgileEAS.NET SOA 中间件平台.Net Socket通信框架-简单例子-实现简单的服务端客户端消息应答

    一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...

  4. mysql定时任务简单例子

    mysql定时任务简单例子 ? 1 2 3 4 5 6 7 8 9     如果要每30秒执行以下语句:   [sql] update userinfo set endtime = now() WHE ...

  5. java socket编程开发简单例子 与 nio非阻塞通道

    基本socket编程 1.以下只是简单例子,没有用多线程处理,只能一发一收(由于scan.nextLine()线程会进入等待状态),使用时可以根据具体项目功能进行优化处理 2.以下代码使用了1.8新特 ...

  6. 一个简单例子:贫血模型or领域模型

    转:一个简单例子:贫血模型or领域模型 贫血模型 我们首先用贫血模型来实现.所谓贫血模型就是模型对象之间存在完整的关联(可能存在多余的关联),但是对象除了get和set方外外几乎就没有其它的方法,整个 ...

  7. Oracle创建自增字段方法-ORACLE SEQUENCE的简单介绍

    引用自 :http://www.2cto.com/database/201307/224836.html   Oracle创建自增字段方法-ORACLE SEQUENCE的简单介绍 先假设有这么一个表 ...

  8. NHibernate的简单例子

    NHibernate的简单例子 @(编程) [TOC] 因为项目需求,搭了一个NHibernate的例子,中间遇到了一些问题,通过各种方法解决了,在这里记录一下最后的结果. 1. 需要的dll Com ...

  9. java 使用 comet4j 主动向客户端推送信息 简单例子

    [背景] 今天,一个前端的师弟问我怎样做实时聊天窗口,我毫不犹豫地说:在前台定时访问服务端呀!师弟默默地百度了一番,最后告诉我,有一种技术是后服务端动推送信息给客户端的,这种技术的名字叫comet,我 ...

随机推荐

  1. FCL研究-集合- System.Collections 接口和对象集合

    [目录] 发现自己已经有很长一段时间写代码没什么进步了,随便读读FCL的源码,看看之前一直用的方法是如何实现的,也顺便提高下自己.FCL很是庞大,很难下口,于是用最笨的办法,先看常见的命名空间,逐个展 ...

  2. 十. 图形界面(GUI)设计7.文本框和文本区的输入输出

    在GUI中,常用文本框和文本区实现数据的输入和输出.如果采用文本区输入,通常另设一个数据输入完成按钮.当数据输入结束时,点击这个按钮.事件处理程序利用getText()方法从文本区中读取字符串信息.对 ...

  3. delphi设计浮动窗口

    delphi设计浮动窗口 用过Photoshop的朋友一定对它的那些方便的浮动面板记忆犹新,其实这些面板就是一个个的小窗体,但这些小窗体都放在Photoshop的主窗体上 (不是存在主窗体中),有自己 ...

  4. Qemu 有用的链接

    Qemu下载和编译 Download https://en.wikibooks.org/wiki/QEMU/Linux https://en.wikibooks.org/wiki/QEMU/Insta ...

  5. github清理,记录一些有趣的项目

    1. rhino 一种java做的开源javascript引擎 https://github.com/mozilla/rhino 2. jeewx 国人写的公众号管理后台,集成度有些高,不好剥离.还是 ...

  6. Tomcat环境下配置数据源

    两种方式,图形化和字符型配置,图形化需要部署一个应用,字符型配置如下: 需要文件 mysql-connector-java-5.1.16-bin.jar Oracle需要classes12.jar文件 ...

  7. Oracle导入本属于sys用户的表

    FlashBack Database后,将删除的数据导出时使用了system用户 exp system/oracle file=/home/oracle/test.dmp tables=sys.tes ...

  8. macOS中Vim基本配置,颜色主题/语法/indent设置

    macOS中Vim基本配置 Vim的初始化配置 .vimrc 存放位置 macOS 环境下 vim 的初始化配置文件为 .vimrc , 通常有两个(系统版本和用户版本),一个位于 /usr/shar ...

  9. Gitlab系列八之重置管理员密码

    gitlab web登入密码忘记以后可以用如下方式修改密码 [root@gitlat-test gitlab]# gitlab-rails console production Loading pro ...

  10. mongodb 踩坑记录

    Map-Reduce Map-Reduce 是 mongodb 处理批量数据的大杀器,凡是数据量大并且定时处理能满足需求的,都可以试着扔给 mongodb,让它去 Map-Reduce. 以下截取自文 ...