关于runtime2

1.动态给分类添加属性,
2.方法的交换swizzling,
3.字典转模型,
4.获取所有的私有属性和方法",
5.对私有属性修改,
 6.归档解档,
 7.动态添加方法"

 

一、Method Swizzling

Method Swizzling是改变一个已存在的selector的实现的技术。可以使用它来在Runtime通过修改类的分发表中selector对应的函数,来修改selector的实现。我们常用Method Swizzling来将系统的方法换为我们自定义的方法,给系统方法添加一些需要的功能,来实现某些需求。例如,跟踪程序每个ViewController展示给用户的次数,可以通过Method Swizzling替换ViewDidAppear初始方法。再例如更换全局UILabel默认字体,可以通过Method Swizzling替换UILabel初始方法来修改等。

实例

因为Method Swizzling的实现模式比较固定,所以将其抽象为一个分类,可以直接方便调用.

NSObject Category

#import <Foundation/Foundation.h>

@interface NSObject (Swizzling)

+(void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector;

@end

#import "NSObject+Swizzling.h"

#import <objc/runtime.h>

@implementation NSObject (Swizzling)

+(void)methodSwizzlingWithOriginalSelector:(SEL)originalSelector bySwizzledSelector:(SEL)swizzledSelector{ Class class = [self class];

Method originalMethod = class_getInstanceMethod(class, originalSelector);

Method swizzleMethod=class_getInstanceMethod(class, swizzledSelector);

BOOL didAddMethod=class_addMethod(class,originalSelector,method_getImplementation(swizzleMethod), method_getTypeEncoding(swizzleMethod));

if (didAddMethod)

{ class_replaceMethod(class, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod));

}else{

method_exchangeImplementations(originalMethod, swizzleMethod);

} }

@end

 

二。给分类添加属性

为UIImage类添加一个downLoadURL的属性。

#import <UIKit/UIKit.h>

@interface UIImage (downLoadURL)

@property (nonatomic, strong) NSString *downLoadURL;

@end

#import "UIImage+downLoadURL.h"

#import <objc/runtime.h>

@implementation UIImage (downLoadURL)

-(void)setDownLoadURL:(NSString *)downLoadURL{

objc_setAssociatedObject(self, @selector(downLoadURL), downLoadURL, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -(NSString *)downLoadURL{

return objc_getAssociatedObject(self, @selector(downLoadURL));

}

@end



 



 



 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值