iOS类的属性研究

定义一个类并定义一些属性用来测试。

@interface SKTestClassProperty : NSObject
/**
 *  @brief 测试字符串属性   "T@\"NSString\",C,V_name"
 */
@property (nonatomic, copy) NSString *name;
/**
 *  @brief 测试整形属性    NSInteger Tq,N,V_price     CGFloat Td,N,V_price  BOOL TB,N,V_price  int Ti,N,V_price
 */
@property (nonatomic, assign) NSInteger price;
/**
 *  @brief 测试字典属性  T@\"NSArray\",C,N,V_peopertyArray
 */
@property (nonatomic, copy) NSArray *peopertyArray;
/**
 *  @brief 属性字典
 *
 *  @return dic
 */
- (NSDictionary *)propertyDict;

@end

实现:

#import "SKTestClassProperty.h"
#import <objc/runtime.h>
@implementation SKTestClassProperty

-(NSDictionary *)propertyDict {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    unsigned int  count = 0;
    
  //  Describes the properties declared by a class. 描述了一个类里的属性 返回的是一个数组
    // OBJC_EXPORT objc_property_t *class_copyPropertyList(Class cls, unsigned int *outCount)
    /**
     *  @brief
     *
     *  @param class] class 是你想要确认属性的类
     *  @param count  这个count 是返回值 如果不为空的时候返回一个数组 某则返回 0
     *
     *  @return 返回的类型是一个带有objc_property_t 属性类型的数组。
     */
    objc_property_t *propertyes = class_copyPropertyList([self class], &count);
    for (NSInteger i = 0 ; i < count; i ++) {
        /**
         *  @brief  获取参数名
         *
         *  @param propertyes 返回属性总属性的数组
         *
         *  @return 参数名
         */
        const char *name = property_getName(propertyes[i]);
        /**
         *  @brief 获取属性
         *
         *  @param propertyes
         *
         *  @return 属性
         */
        const char *attribuate = property_getAttributes(propertyes[i]);
        NSString *contentName = [NSString stringWithUTF8String:name];
        NSString *attribuateName = [NSString stringWithFormat:@"%s",attribuate];
        [dict setValue:attribuateName forKey:contentName];
        
    }
    
    return dict;
}
/**
 *  @brief  打印出的是这个样子的
 {
 name = "T@\"NSString\",C,N,V_name";
 peopertyArray = "T@\"NSArray\",C,N,V_peopertyArray";
 price = "Tq,N,V_price";
 }
T  C  N  V 是苹果提供的编码   苹果对每个变量的类型进行了编码 同样对方法也进行了编码

 name = "T@\"NSString\",C,N,V_name";  表示这是一个NSString 类型的属性 C 代表了copy N代表了nontamic  V_name 是变量的名字 这里苹果对名字也进行了编码

 */
@end
- (void)viewDidLoad {
    
    [super viewDidLoad];

    SKTestClassProperty *class = [[SKTestClassProperty alloc]init];
    NSLog(@"%@",[class propertyDict]);
    
}

控制台打印结果:

{
    name = "T@\"NSString\",C,N,V_name";
    peopertyArray = "T@\"NSArray\",C,N,V_peopertyArray";
    price = "Tq,N,V_price";
}

上述编码地址在这里

comments powered by Disqus