运行时机制是纯C语言,平时写得OC代码最终都要转成C运行时代码
@property在category中只能实现get,set方法的声明,不能实现方法的实现
#import <objc/message.h>
objc_setAssociatedObject(<#id object#>, <#const void *key#>, <#id value#>, <#objc_AssociationPolicy policy#>)
static int heightKey;
代码如下:
// Person.h
// 运行时机制
//
// Created by 殷婷婷 on 15-6-10.
// Copyright (c) 2015年 lanou. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,assign)int age;
@end
#import "Person.h"
@implementation Person
@end
#import "Person.h"
@interface Person (YTT)
@property(nonatomic,assign)double height;
@end
@implementation Person (YTT)
static double heightKey;
- (void)setHeight:(double)height{
objc_setAssociatedObject(self, &heightKey, @(height), OBJC_ASSOCIATION_ASSIGN); //会把height的值赋值到heightKey里
}
- (double)height{
return [objc_getAssociatedObject(self, &heightKey) doubleValue];
}
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Person+YTT.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
Person *p = [[Person alloc]init];
p.height = 30;
NSLog(@"%d",p.age);
NSLog(@"%f",p.height);
}
return 0;
}
结果:
2015-06-10 19:30:37.743 运行时机制[5631:303] 0
2015-06-10 19:30:37.744 运行时机制[5631:303] 30.000000
Program ended with exit code: 0
========================遍历成员变量===========================
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property(nonatomic,assign)int age;
@property(nonatomic,copy)NSString *name;
@end
#import <Foundation/Foundation.h>
#import "Person.h"
#import "Person+YTT.h"
#import <objc/runtime.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
unsigned int count = 0;
//获得Person类中的所有成员变量
Ivar *ivars = class_copyIvarList([Person class], &count);
//遍历所有成员变量
for (int i = 0; i < count; i++) {
Ivar ivar = ivars[i];
const char *name = ivar_getName(ivar);
const char *type = ivar_getTypeEncoding(ivar);
NSLog(@"%s,%s",name,type);
}
2015-06-10 19:48:39.229 运行时机制[5704:303] _age,i
2015-06-10 19:48:39.231 运行时机制[5704:303] _name,@"NSString"
class_copyIvarList(<#__unsafe_unretained Class cls#>, <#unsigned int *outCount#>)