iOS 獲取某個類的全部屬性以及方法

在我們的工作中有時候需要獲取某些sdk未提供的屬性以及方法 ,這個時候應該怎么辦呢?
可以通過以下方法獲取

  • 獲取類的方法
    + (void)LogAllMethodsFromClass:(id)obj
    {
    u_int count;
    //class_copyMethodList 獲取類的所有方法列表
    Method *mothList_f = class_copyMethodList([obj class],&count) ;
    for (int i = 0; i < count; i++) {
    Method temp_f = mothList_f[i];
    // method_getImplementation 由Method得到IMP函數指針
    IMP imp_f = method_getImplementation(temp_f);

            // method_getName由Method得到SEL
            SEL name_f = method_getName(temp_f);
      
            const char * name_s = sel_getName(name_f);
            // method_getNumberOfArguments  由Method得到參數個數
            int arguments = method_getNumberOfArguments(temp_f);
            // method_getTypeEncoding  由Method得到Encoding 類型
            const char * encoding = method_getTypeEncoding(temp_f);
      
            NSLog(@"方法名:%@\n,參數個數:%d\n,編碼方式:%@\n",[NSString stringWithUTF8String:name_s],
            arguments,[NSString stringWithUTF8String:encoding]);
        }
        free(mothList_f);
    
    }
    
  • 獲取類的屬性
    + (NSArray *)getAllProperties:(id)obj
    {
    u_int count;

      //使用class_copyPropertyList及property_getName獲取類的屬性列表及每個屬性的名稱
    
        objc_property_t *properties  =class_copyPropertyList([obj class], &count);
        NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++)
        {
            const char* propertyName =property_getName(properties[i]);
            NSLog(@"屬性%@\n",[NSString stringWithUTF8String: propertyName]);
            [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
        }
        free(properties);
        return propertiesArray;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容