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