iOS 类增加成员变量

RT

(AddProperty)@property (nonatomic,strong) NSString *stringProperty;@property (nonatomic,assign) NSInteger integerProperty;@end*StringProperty = &StringProperty;*IntegerProperty = &IntegerProperty;(AddProperty)@dynamic stringProperty;//set-(void)setStringProperty:(NSString *)stringProperty{//use that a static const as the keyobjc_setAssociatedObject(self, StringProperty, stringProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);//use that property’s selector as the key://objc_setAssociatedObject(self, @selector(stringProperty), stringProperty, OBJC_ASSOCIATION_RETAIN_NONATOMIC);}//get-(NSString *)stringProperty{return objc_getAssociatedObject(self, StringProperty);}//set-(void)setIntegerProperty:(NSInteger)integerProperty{NSNumber *number = [[NSNumber alloc]initWithInteger:integerProperty];objc_setAssociatedObject(self, IntegerProperty, number, OBJC_ASSOCIATION_ASSIGN);}//get-(NSInteger)integerProperty{return [objc_getAssociatedObject(self, IntegerProperty) integerValue];}@end

// 获取成员变量列表

@interface NSObject (Property)-(NSDictionary *)propertyDictionary;+ (NSArray *)classPropertyList;@end@implementation NSObject (Property)-(NSDictionary *)propertyDictionary{//创建可变字典NSMutableDictionary *dict = [NSMutableDictionary dictionary];unsigned int outCount;objc_property_t *props = class_copyPropertyList([self class], &outCount);for(int i=0;i<outCount;i++){objc_property_t prop = props[i];NSString *propName = [[NSString alloc]initWithCString:property_getName(prop) encoding:NSUTF8StringEncoding];id propValue = [self valueForKey:propName];if(propValue){[dict setObject:propValue forKey:propName];}}free(props);return dict;}+ (NSArray *)classPropertyList {NSMutableArray *allProperties = [[NSMutableArray alloc] init];unsigned int outCount;objc_property_t *props = class_copyPropertyList(self, &outCount);for (int i = 0; i < outCount; i++) {objc_property_t prop = props[i];NSString *propName = [[NSString alloc]initWithCString:property_getName(prop) encoding:NSUTF8StringEncoding];if (propName) {[allProperties addObject:propName];}}free(props);return [NSArray arrayWithArray:allProperties];}@end

原文地址:https://github.com/shaojiankui/iOS-Categories/tree/master/Categories/Foundation/NSObject

,人生最好的旅行,就是你在一个陌生的地方,

iOS 类增加成员变量

相关文章:

    你感兴趣的文章:

    标签云: