标签:
#import <Foundation/Foundation.h>
#import "Student.h"
//引入runtime底层框架
#import <objc/runtime.h>
#import "Student+EnglishName.h"
//动态添加的方法的声名
void happyWithGirl(id self ,SEL _cmd);
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
Student *stu = [[Student alloc] init];
stu.name = @"小明";
stu.age = 18;
[stu learnSomeThing];
[stu playGames];
NSLog(@"stu.name:%@",stu.name);
NSLog(@"stu.age:%d",stu.age);
NSLog(@"===============================");
//runtime 动态获取对象的属性
unsigned int count;
Ivar *vars = class_copyIvarList([Student class], &count);
for (int i=0; i<count; i++) {
char *varName = ivar_getName(vars[i]);
NSLog(@"varName:%s",varName);
NSString *str = [[NSString alloc] initWithCString:varName encoding:NSUTF8StringEncoding];
if ([str isEqualToString:@"_name"]) {
/**
参数1 具体要修改的对象
参数2 要修改哪一个属性
参数3 修改的值
*/
object_setIvar(stu, vars[i], @"小强");
}
}
NSLog(@"stu.name:%@",stu.name);
//runtime 动态交换方法实现
//动态获取学习方法
Method *learnn = class_getInstanceMethod([Student class], @selector(learnSomeThing));
//动态获取玩方法
Method *game = class_getInstanceMethod([Student class], @selector(playGames));
//动态交换两个方法
method_exchangeImplementations(learnn, game);
NSLog(@"以下是调用了学习方法:");
[stu learnSomeThing];
//动态添加方法
/**
参数1 给具体哪一个类添加方法
参数2 添加的方法名字
参数3 是该方法的具体实现方法
参数3 是参数的返回值类型
*/
class_addMethod([Student class], @selector(makeGirlFriend), (IMP)happyWithGirl, "v@:");
//动态调用交女朋友方法
[stu performSelector:@selector(makeGirlFriend)];
//调用动态为category扩展添加的属性
stu.englishName = @"jone";
NSLog(@"动态为category添加的属性值为:%@",stu.englishName);
}
return 0;
}
void happyWithGirl(id self ,SEL _cmd){
NSLog(@"交女朋友很高兴!");
}
#import <Foundation/Foundation.h>
@interface Student : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,assign) int age;
//学习
-(void)learnSomeThing;
//玩
-(void)playGames;
@end
#import "Student.h"
@implementation Student
-(void)learnSomeThing{
NSLog(@"学习了一些知识");
}
-(void)playGames{
NSLog(@"玩了一宿游戏");
}
@end
#import "Student.h"
@interface Student (EnglishName)
@property (nonatomic,strong)NSString *englishName;
@end
#import "Student+EnglishName.h"
#import <objc/runtime.h>
@implementation Student (EnglishName)
//重写get,set方法
char eName;
-(void)setEnglishName:(NSString *)englishName{
objc_setAssociatedObject(self, &eName, englishName, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)englishName{
return objc_getAssociatedObject(self, &eName);
}
@end
标签:
原文地址:http://www.cnblogs.com/lan1x/p/5329855.html