IOS 中runtime使用方法整理
做iOS的朋友都知道或听说runtime,这个东西很像java的反射机制,但功能远胜于java的反射。通过runtime我们可以动态的向一个类中添加属性、成员变量、方法,以及对其进行读写访问。
新建两个类ClassOne和ClassTwo
#import <Foundation/Foundation.h>
@interface ClassOne : NSObject{
NSString *_publicVar1;
NSString *_publicVar2;
}
@property(nonatomic,copy) NSString *publicProperty1;
@property(nonatomic,copy) NSString *publicProperty2;
- (void) testClassOneWithArg1:(NSString *)arg1;
@end
#import "ClassOne.h"
@interface ClassOne()
@property(nonatomic,copy) NSString *privateProperty1;
@property(nonatomic,copy) NSString *privateProperty2;
@end
@implementation ClassOne{
NSString *_privateVar1;
NSString *_privateVar2;
}
- (void)testClassOneWithArg1:(NSString *)arg1{
NSLog(@"this is CalssOne, arg1:%@",arg1);
}
- (void)testClassOneWithArg1:(NSString *)arg1 arg2:arg2{
NSLog(@"this is CalssOne, arg1:%@ arg2:%@",arg1,arg2);
}
@end
#import <Foundation/Foundation.h>
@interface ClassTwo : NSObject
- (void) testClassTwoWithArg1:(NSString *)arg1 arg2:(NSString *)arg2;
@end
#import "ClassTwo.h"
@implementation ClassTwo
- (void)testClassTwoWithArg1:(NSString *)arg1 arg2:(NSString *)arg2{
NSLog(@"this is ClassTwo arg1:%@,arg2:%@",arg1,arg2);
}
@end
1.拷贝对象
ClassOne *one = [ClassOne new];
id onec1 = object_copy(one,sizeof(one));
2.给类添加方法
ClassOne *one = [ClassOne new];
class_addMethod([ClassOne class], @selector(testClassOneWithArg1:arg2:arg3:), (IMP)testClassOne , "i@:@@@");
[one testClassOneWithArg1:@"arg1" arg2:@"arg2" arg3:@"arg3"];
//方法对应的C函数
int testClassOne(id self,SEL _cmd, NSString *arg1,NSString *arg2,NSString *arg3){
NSLog(@"this is a test function add to ClassOne as a methad with arg1:%@ arg2:%@ and arg3:%@",arg1,arg2,arg3);
return 10;
}
3.添加属性(方式一)
//属性类型
objc_property_attribute_t type = { "T", "@"NSString"" };
//访问类型
objc_property_attribute_t ownership = { "C", "" };
//对应成员变量名称
objc_property_attribute_t backingivar = { "V", "_testPropertyName" };
objc_property_attribute_t attrs[] = { type, ownership, backingivar };
class_addProperty([ClassOne class], "testPropertyName", attrs, 3);
class_addMethod([ClassOne class], @selector(testPropertyName), (IMP)testPropertyNameGetter , "@:@@");
class_addMethod([ClassOne class], @selector(setTestPropertyName:), (IMP)testPropertyNameSetter, "v:@@@");
//属性对应的Getter方法
NSString* testPropertyNameGetter(id self,SEL _cmd){
Ivar ivar = class_getInstanceVariable([ClassOne class], "_testPropertyName");
return object_getIvar(self, ivar);
}
//属性对应的Setter方法
void testPropertyNameSetter(id self,SEL _cmd,NSString *testPropertyNameValue){
Ivar ivar = class_getInstanceVariable([ClassOne class], "_testPropertyName");
object_setIvar(self, ivar, testPropertyNameValue);
}










