This blog, directly from the classification. All know that the classification in OC can not directly add attributes, meaning indirectly can add attributes. So how do you add it? It's going to use the runtime mechanism.
One, one of the usage of the Golden Code at runtime
Now, add a category to the Hgperson class: Hgperson+hg.h, give a property as follows:
@property (nonatomic, copy) nsstring* name;
Looks like, after this writing, is able to call, but the operation of the error.
-[hgperson SetName:]: Unrecognized selector sent to instance 0x7f90b2e13620
2015-10-02 20:41:28.803 runtime[3357:285701] * * * terminating app due to uncaught exception ' Nsinvalidargumentexception ', Reason: '-[hgperson setName:]: Unrecognized selector sent to instance 0x7f90b2e13620 '
It means that this method has not been found:-[hgperson setName:] .... Oh, I see. There is no implementation in the classification, so the error.
Now we start to use the OC Runtime mechanism to dynamically add member variables to a class. Code is as follows:
#import "Hgperson+hg.h"
#import <objc/message.h>
@implementation Hgperson (HG)
/**
Dynamically add a member variable to this class
*/
This key is used for reference < I'm not too clear, not a member variable
static double Namekey;
-(void) SetName: (NSString *) name {
Objc_setassociatedobject (self, &namekey, name, objc_association_copy_nonatomic);
}
-(NSString *) name {
Return Objc_getassociatedobject (self, &namekey);
}
@end
Second, the use of the Golden Code in the operation of the second
Record the number of member variables in the Hgperson class
Nsinteger count;
Get a list of all member variables in the Hgperson class
ivar* Ivars = class_copyivarlist (Objc_getclass ("Hgperson"), &count);
Traversing member variables in the Hgperson class
for (Nsinteger i=0; i<count; i++) {
Ivar IAVR = ivars[i];
Const char* name = Ivar_getname (IAVR);
Const char* type = ivar_gettypeencoding (IAVR);
}
An analysis of IOS runtime (runtime)