Rt
// 增加成员变量#import <Foundation/Foundation.h>@interface NSObject (AddProperty)@property (nonatomic,strongNSString *stringProperty;@property (nonatomic,assignNSInteger integerProperty;@end
#import "Nsobject+addproperty.h" #import <objc/runtime.h> both//objc_getassociatedobject and objc_setassociatedobject need to specify a fixed address, which is used to represent the key of the attribute and act as a constant. Static Const void*stringproperty = &StringProperty;Static Const void*integerproperty = &IntegerProperty;//static Char integerproperty; @implementation nsobject (addproperty)@dynamicStringproperty;//set-(void) Setstringproperty: (NSString*) stringproperty{//use that a static const as the keyObjc_setassociatedobject ( Self, Stringproperty, Stringproperty, objc_association_retain_nonatomic);//use ' s selector as the key: //objc_setassociatedobject (Self, @selector (stringproperty), Stringproperty, objc_association_retain_nonatomic );}//get-(NSString*) stringproperty{returnObjc_getassociatedobject ( Self, Stringproperty);}//set-(void) Setintegerproperty: (Nsinteger) integerproperty{NSNumber*number = [[NSNumberAlloc]initwithinteger:integerproperty]; Objc_setassociatedobject ( Self, Integerproperty, number, objc_association_assign);}//get-(Nsinteger) integerproperty{return[Objc_getassociatedobject ( Self, Integerproperty) IntegerValue];}@end
Get a list of member variables
@interface NSObject (Property)-(NSDictionary *)propertyDictionary;+ (NSArray *)classPropertyList;@end
#import "Nsobject+property.h" #import <Foundation/Foundation.h> #import <objc/runtime.h> @implementation nsobject (property)-(nsdictionary*) propertydictionary{//Create a mutable dictionary nsmutabledictionary*dict = [nsmutabledictionaryDictionary];unsigned intOutcount; objc_property_t *props = Class_copypropertylist ([ SelfClass], &outcount); for(intI=0; i<outcount;i++) {objc_property_t prop = Props[i];NSString*propname = [[NSStringAlloc]initwithcstring:property_getname (prop) encoding:nsutf8stringencoding];IDPropValue = [ SelfValueforkey:propname];if(PropValue) {[Dict setobject:propvalue forkey:propname]; }} free (props);returnDict;} + (Nsarray*) Classpropertylist {Nsmutablearray*allproperties = [[NsmutablearrayALLOC] init];unsigned intOutcount; objc_property_t *props = Class_copypropertylist ( Self, &outcount); for(inti =0; i < Outcount; i++) {objc_property_t prop = Props[i];NSString*propname = [[NSStringAlloc]initwithcstring:property_getname (prop) encoding:nsutf8stringencoding];if(propname) {[Allproperties addobject:propname]; }} free (props);return[NsarrayArraywitharray:allproperties];}@end
Original address: Https://github.com/shaojiankui/iOS-Categories/tree/master/Categories/Foundation/NSObject
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
IOS class Add member variable