在我們的工作中有時(shí)候需要獲取某些sdk未提供的屬性以及方法 ,這個(gè)時(shí)候應(yīng)該怎么辦呢?
可以通過(guò)以下方法獲取
-
獲取類的方法
+ (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函數(shù)指針
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得到參數(shù)個(gè)數(shù) int arguments = method_getNumberOfArguments(temp_f); // method_getTypeEncoding 由Method得到Encoding 類型 const char * encoding = method_getTypeEncoding(temp_f); NSLog(@"方法名:%@\n,參數(shù)個(gè)數(shù):%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獲取類的屬性列表及每個(gè)屬性的名稱 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; }