1. 程式人生 > >OC執行時獲取物件的所有屬性、所有方法

OC執行時獲取物件的所有屬性、所有方法

一、建立NSObject的Category檔案。引入runtime標頭檔案。

Runtime各種方法屬性參見:http://blog.csdn.net/sharktoping/article/details/59486347

#import <objc/runtime.h>

 獲取物件的所有屬性

+ (NSArray *)getAllProperties{

    u_int count = 0;

//傳遞count的地址

  objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *propertyArray = [NSMutableArray arrayWithCapacity:count];

    for (int i = 0; i < count; i++) {

//得到的propertyName為C語言的字串

        const char *propertyName = property_getName(properties[i]);

        [propertyArray addObject:[NSString stringWithUTF8String:propertyName]];

// NSLog(@"%@",[NSString stringWithUTF8String:propertyName]);

    }

    free(properties);

    return propertyArray;

}

 //獲取物件的所有方法

+ (NSArray *)getAllMethods{

    unsigned int methodCount = 0;

    Method *methodList = class_copyMethodList([self class], &methodCount);

  NSMutableArray *methodArray = [NSMutableArray arrayWithCapacity:methodCount];

    for (int i = 0; i < methodCount; i++) {

        Method temp = methodList[i];

        SEL name_F = method_getName(temp);

        const char *name_s = sel_getName(name_F);

        int arguments = method_getNumberOfArguments(temp);

        const char * encoding = method_getTypeEncoding(temp);

//  NSLog(@"MethodName: %@,ArgumentCount: %d,EncodingStyle: %@",[NSString stringWithUTF8String:name_s],arguments,[NSString stringWithUTF8String:encoding]);

        [methodArray addObject:[NSString stringWithUTF8String:name_s]];

    }

    free(methodList);

    return methodArray;

}

//呼叫

NSLog(@"%@",[UITextField getAllProperties]);