1动态改变属性
Person定义如下
@interface Person : NSObject
{
NSString *age;
}
@property(nonatomic,copy) NSString *name;
@property(nonatomic,copy) NSString *sex;
-(NSString *)sayName;
-(NSString *)saySex;
@end
下面是代码片段
self.person = [Person new];
_person.name = @"liju";
unsigned int count = 0;
objc_property_t *ivar = class_copyPropertyList([self.person class], &count);//仅仅是对象类的属性(@property申明的属性)
//这个遍历里面就访问不到age属性
动态增加方法
- (void)dynamicAddMethod
{
class_addMethod([Person class], @selector(guess), class_getMethodImplementation([UIViewController class], @selector(guess)), "v@:");
if ([self.person respondsToSelector:@selector(guess)]) {
[self.person performSelector:@selector(guess)];//调用增加的方法
} else{
NSLog(@"无此方法");
}
}
-(void)guess{
NSLog(@"6666");
}
//动态增加属性的方法
- (void)addStrPropertyForTargetClass:(Class)targetClass Name:(NSString *)propertyName{
objc_property_attribute_t type = { "T", [[NSString stringWithFormat:@"@\"%@\"",NSStringFromClass([NSString class])] UTF8String] }; //type
objc_property_attribute_t ownership0 = { "C", "" }; // C = copy
objc_property_attribute_t ownership = { "N", "" }; //N = nonatomic
objc_property_attribute_t backingivar = { "V", [[NSString stringWithFormat:@"_%@", propertyName] UTF8String] }; //variable name
objc_property_attribute_t attrs[] = { type, ownership0, ownership, backingivar };
class_addProperty(targetClass, [propertyName UTF8String], attrs, 4);
}
动态增加成员变量
class_addIvar([self.person class], "country", sizeof(NSString *), 0, "@"); //这个方法没有增加上 不知道为什么望知道的亲们说一下
//动态交换二个方法的实现
Method methodOne = class_getInstanceMethod([self.person class], @selector(sayName));
Method methodTwo = class_getInstanceMethod([self.person class], @selector(saySex));
method_exchangeImplementations(methodOne, methodTwo);
//拦截并替换方法 Person里面的sayName方法被Tool类里面的changeMethod替换了
Method m1 = class_getInstanceMethod([Person class], @selector(sayName));
Method m2 = class_getInstanceMethod([Tool class], @selector(changeMethod));
method_exchangeImplementations(m1, m2);