runtime獲取類屬性列表和方法列表

獲取對象的所有屬性

/* 獲取對象的所有屬性 */
+(NSArray *)getAllProperties
{
    u_int count;
    // 傳遞count的地址過去 &count
    objc_property_t *properties  =class_copyPropertyList([self class], &count);
    //arrayWithCapacity的效率稍微高那么一丟丟
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];

    for (int i = 0; i < count ; i++)
    {
        //此刻得到的propertyName為c語言的字符串
        const char* propertyName =property_getName(properties[i]);
        //此步驟把c語言的字符串轉換為OC的NSString
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    //class_copyPropertyList底層為C語言,所以我們一定要記得釋放properties
    // You must free the array with free().
    free(properties);

    return propertiesArray;
}  ```
#### 獲取對象所有方法

/* 獲取對象的所有方法 */
+(NSArray )getAllMethods
{
unsigned int methodCount =0;
Method
methodList = class_copyMethodList([self class],&methodCount);
NSMutableArray *methodsArray = [NSMutableArray arrayWithCapacity:methodCount];

for(int i=0;i<methodCount;i++)
{
    Method temp = methodList[i];
    IMP imp = method_getImplementation(temp);
    SEL name_f = method_getName(temp);
    const char* name_s =sel_getName(method_getName(temp));
    int arguments = method_getNumberOfArguments(temp);
    const char* encoding =method_getTypeEncoding(temp);
    NSLog(@"方法名:%@,參數個數:%d,編碼方式:%@",[NSString stringWithUTF8String:name_s],
          arguments,
          [NSString stringWithUTF8String:encoding]);
    [methodsArray addObject:[NSString stringWithUTF8String:name_s]];
}
free(methodList);
return methodsArray;

} ```

獲取對象的所有屬性和屬性內容

/* 獲取對象的所有屬性和屬性內容 */
+ (NSDictionary *)getAllPropertiesAndVaules:(NSObject *)obj
{
    NSMutableDictionary *propsDic = [NSMutableDictionary dictionary];
    unsigned int outCount;
    objc_property_t *properties =class_copyPropertyList([obj class], &outCount);
    for ( int i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [obj valueForKey:(NSString *)propertyName];
        if (propertyValue) {
            [propsDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return propsDic;
} ```

#### 用的時候記得導入頭文件

import <objc/runtime.h> ```

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,915評論 18 139
  • 國家電網公司企業標準(Q/GDW)- 面向對象的用電信息數據交換協議 - 報批稿:20170802 前言: 排版 ...
    庭說閱讀 11,141評論 6 13
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,242評論 25 708
  • 1.對于推送證書,只要生成新的推送證書,并將p.12文件傳至相應推送開放平臺即可。2.對于發布證書,過期不會影響線...
    ONE2閱讀 6,223評論 0 1
  • GaryZhang閱讀 690評論 0 51