利用runtime獲取對象的所有屬性(值),所有方法

首先奉上demo的地址
https://github.com/MyHZ/HZCoding.git
還有 pod 'NSObject+HZCoding'

接下來直接上代碼了

新建一個類別
NSObject+HZCoding

然后聲明和實現(xiàn)如下方法

1.獲取對象的所有屬性

/* 獲取對象的所有屬性 */
-(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語言的字符串轉(zhuǎn)換為OC的NSString
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    //class_copyPropertyList底層為C語言,所以我們一定要記得釋放properties
    // You must free the array with free().
    free(properties);
    
    return propertiesArray;
}
  1. 獲取對象的所有方法
/* 獲取對象的所有方法 */
-(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];
        const char* name_s =sel_getName(method_getName(temp));
        int arguments = method_getNumberOfArguments(temp);
        const char* encoding =method_getTypeEncoding(temp);
        NSLog(@"方法名:%@,參數(shù)個數(shù):%d,編碼方式:%@",[NSString stringWithUTF8String:name_s],
              arguments,
              [NSString stringWithUTF8String:encoding]);
        [methodsArray addObject:[NSString stringWithUTF8String:name_s]];
    }
    free(methodList);
    return methodsArray;
}

3.獲取對象的所有屬性和屬性內(nèi)容

/* 獲取對象的所有屬性和屬性內(nèi)容 */
-(NSDictionary *)getAllPropertiesAndVaules
{
    NSMutableDictionary *propsDic = [NSMutableDictionary dictionary];
    unsigned int outCount;
    objc_property_t *properties =class_copyPropertyList([self 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 = [self valueForKey:(NSString *)propertyName];
        if (propertyValue) {
            [propsDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return propsDic;
}

打個廣告
一句話 利用runtime輕松實現(xiàn) 歸檔解檔:http://www.itdecent.cn/p/14d0190a83d5

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容