獲取對象的所有屬性
/* 獲取對象的所有屬性 */
+(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;
} ```
#### 用的時候記得導入頭文件