iOS 类增加成员变量

来源:互联网 发布:encore软件 编辑:程序博客网 时间:2024/05/16 03:12

RT

// 增加成员变量#import <Foundation/Foundation.h>@interface NSObject (AddProperty)@property (nonatomic,strong) NSString *stringProperty;@property (nonatomic,assign) NSInteger integerProperty;@end
#import "NSObject+AddProperty.h"#import <objc/runtime.h>//objc_getAssociatedObject和objc_setAssociatedObject都需要指定一个固定的地址,这个固定的地址值用来表示属性的key,起到一个常量的作用。static const void *StringProperty = &StringProperty;static const void *IntegerProperty = &IntegerProperty;//static char IntegerProperty;@implementation NSObject (AddProperty)@dynamic stringProperty;//set-(void)setStringProperty:(NSString *)stringProperty{    //use that a static const as the key    objc_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
#import "NSObject+Property.h"#import <Foundation/Foundation.h>#import <objc/runtime.h>@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

0 0
原创粉丝点击