Run-time mechanism is pure C language, usually written OC code will eventually be converted to C run-time code
@property can only implement the declaration of Get,set method in category, can't implement the method
#import <objc/message.h>
Objc_setassociatedobject (< #id Object#>, < #const void *key#>, < #id Value#>, < #objc_ Associationpolicy policy#>)
static int heightkey;
The code is as follows:
Person.h
Run-time mechanism
//
Created by Sinting 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); Will assign the height value to the 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;
}
Results:
2015-06-10 19:30:37.743 run-time mechanism [5631:303] 0
2015-06-10 19:30:37.744 run-time mechanism [5631:303] 30.000000
Program ended with exit code:0
======================== Traversal member Variable ===========================
#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;
Get all member variables in the person class
Ivar *ivars = class_copyivarlist ([Person class], &count);
Traverse all member variables
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 run-time mechanism [5704:303] _age,i
2015-06-10 19:48:39.231 run-time mechanism [5704:303] _name,@ "NSString"
Class_copyivarlist (< #__unsafe_unretained Class Cls#>, < #unsigned int *outcount#>)
Run-time: :: Classification is not an extensible member variable, you can add member variables dynamically using the run-time mechanism