1. 程式人生 > >iOS 獲取類的全部屬性和全部方法 +(用例拓展:MVC的資料解析==資料對映)

iOS 獲取類的全部屬性和全部方法 +(用例拓展:MVC的資料解析==資料對映)

備註:

#import <objc/runtime.h>

1.獲取類的全部屬性

<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif;"></span><pre name="code" class="html">/**
 *  獲取類的所有屬性
 */
+(void)showStudentClassProperties
{
    Class cls = [Student class];
    unsigned int count;
    while (cls!=[NSObject class]) {
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        for (int i = 0; i<count; i++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            NSLog(@"屬性名==%@",propertyName);
        }
        if (properties){
            //要釋放
           free(properties);
        }
    //得到父類的資訊
    cls = class_getSuperclass(cls);
    }
}


<span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif;">2.獲取類的全部方法</span>
/**
 *  獲取類的所有方法
 */
+(void)showStudentClassMethods
{
    unsigned int count;
    Class cls = [Student class];
    while (cls!=[NSObject class]){
        Method *methods = class_copyMethodList(cls, &count);
        for (int i=0; i < count; i++) {
            NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(methods[i])) encoding:NSUTF8StringEncoding];
            NSLog(@"方法名:%@ ", methodName);
        }
        if (methods) {
             free(methods);
        }
        cls = class_getSuperclass(cls);
    }
   
}
3.獲取類的全部方法
/**
 *  獲取類的所有屬性 做健值反射
 */
+(Student *)showStudentClassPropertiesToMapValueWithDic:(NSDictionary *)dic
{
    Student *stu = [[Student alloc] init];
    
    Class cls = [Student class];
    unsigned int count;
    while (cls!=[NSObject class]) {
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        for (int i = 0; i<count; i++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            //得到屬性名可以在這裡做反射 反饋過來的dic 直接反射成一個model 
            /**
             *  valueForKey: 是 KVC(NSKeyValueCoding) 的方法,在 KVC 裡可以通過 property 同名字串來獲取對應的值
             *  這裡的dic 的key 與 stu 的屬性名一一對應
             * (MVC模式設計資料反射時候用到{類定義屬性時候要和服務端反饋過來的欄位一樣})
             */
            id propertyValue = [dic valueForKey:propertyName];
            if (propertyValue)
                [stu setValue:propertyValue forKey:propertyName];//屬性get set賦值
            // NSLog(@"%@ = %@",propertyName,propertyValue);
        }
        if (properties){
            free(properties);
        }
        //得到父類的資訊
        cls = class_getSuperclass(cls);
    }
    return stu;
}


==========================================================================================================

全部程式碼

.h

//
//  Student.h
//  demo
//
//  Created by linpeng on 14-7-22.
//  Copyright (c) 2014年 linpeng. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface People : NSObject
/**
 *  名字
 */
@property(nonatomic,strong)NSString *name;
/**
 *  性別
 */
@property(nonatomic,strong)NSString *sex;
/**
 *  年齡
 */
@property(nonatomic,)NSInteger age;
@end

/**
 *  //////////////////////////////////////////////////////////////////////////////////////
 */

@interface Student : People
/**
 *  學校
 */
@property(nonatomic,strong)NSString *school;
/**
 *  班級
 */
@property(nonatomic,strong)NSString *classroom;
@end



/**
 *  //////////////////////////////////////////////////////////////////////////////////////
 */

@interface StudentManage : NSObject
+(void)showStudentClassProperties;
+(Student *)showStudentClassPropertiesToMapValueWithDic:(NSDictionary *)dic;
+(void)showStudentClassMethods;
@end












.m
//
//  Student.m
//  demo
//
//  Created by linpeng on 14-7-22.
//  Copyright (c) 2014年 linpeng. All rights reserved.
//

#import "Student.h"
#import <objc/runtime.h>
@implementation People
-(void)pers
{
    
}
@end

@implementation Student
-(void)show
{
    
}
-(void)hide
{
    
}
@end

@implementation StudentManage
/**
 *  獲取類的所有屬性
 */
+(void)showStudentClassProperties
{
    Class cls = [Student class];
    unsigned int count;
    while (cls!=[NSObject class]) {
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        for (int i = 0; i<count; i++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            NSLog(@"屬性名==%@",propertyName);
        }
        if (properties){
            //要釋放
           free(properties);
        }
    //得到父類的資訊
    cls = class_getSuperclass(cls);
    }
}
/**
 *  獲取類的所有屬性 做健值反射
 */
+(Student *)showStudentClassPropertiesToMapValueWithDic:(NSDictionary *)dic
{
    Student *stu = [[Student alloc] init];
    
    Class cls = [Student class];
    unsigned int count;
    while (cls!=[NSObject class]) {
        objc_property_t *properties = class_copyPropertyList(cls, &count);
        for (int i = 0; i<count; i++) {
            objc_property_t property = properties[i];
            NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding];
            //得到屬性名可以在這裡做反射 反饋過來的dic 直接反射成一個model 
            /**
             *  valueForKey: 是 KVC(NSKeyValueCoding) 的方法,在 KVC 裡可以通過 property 同名字串來獲取對應的值
             *  這裡的dic 的key 與 stu 的屬性名一一對應
             * (MVC模式設計資料反射時候用到{類定義屬性時候要和服務端反饋過來的欄位一樣})
             */
            id propertyValue = [dic valueForKey:propertyName];
            if (propertyValue)
                [stu setValue:propertyValue forKey:propertyName];//屬性get set賦值
            // NSLog(@"%@ = %@",propertyName,propertyValue);
        }
        if (properties){
            free(properties);
        }
        //得到父類的資訊
        cls = class_getSuperclass(cls);
    }
    return stu;
}

/**
 *  獲取類的所有方法
 */
+(void)showStudentClassMethods
{
    unsigned int count;
    Class cls = [Student class];
    while (cls!=[NSObject class]){
        Method *methods = class_copyMethodList(cls, &count);
        for (int i=0; i < count; i++) {
            NSString *methodName = [NSString stringWithCString:sel_getName(method_getName(methods[i])) encoding:NSUTF8StringEncoding];
            NSLog(@"方法名:%@ ", methodName);
        }
        if (methods) {
            //要釋放
             free(methods);
        }
        //得到父類的資訊
        cls = class_getSuperclass(cls);
    }
   
}
@end

=========================================

判別這個屬性是否具備get set方法 (重要!以上都要新增這個判別)

            NSString *propertySetMethod = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] capitalizedString]

                                           ,[propertyName substringFromIndex:1]];

            SEL selector = NSSelectorFromString(propertySetMethod);

            if ([model respondsToSelector:selector])

            {

                [model setValue:propertyValue forKey:propertyName];

            }


使用:

 /**
     *  dic 服務端反饋過來的字典物件(學生基本資訊屬性)school name age classroom等等
     *  Student 面向物件的 學生model(屬性和伺服器端反饋過來的屬性--key要一直:school name age classroom等等)
     */
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"廈門大學",@"school",@"屎殼郎情調",@"name",@24,@"age",nil];
    //dic===>model(student)
    Student *stu = [StudentManage showStudentClassPropertiesToMapValueWithDic:dic];
    NSLog(@"基本資訊:%@",stu);
結果