有時我們需要獲取某個類對應(yīng)的屬性聊训,實例方法敬肚,類方法等绑蔫,下面就是個人做的簡單總結(jié):
導(dǎo)入:
#import <objc/message.h>
協(xié)議方法的獲取
- (NSArray<NSString *> *)methodListWithProtocol:(Protocol *)protocol {
unsigned int count = 0;
NSMutableArray<NSString *> *methodList = @[].mutableCopy;
struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, YES, YES, &count);
for (unsigned int i = 0; i < count; i++) {
struct objc_method_description method = methods[i];
NSString *name = NSStringFromSelector(method.name);
[methodList addObject:name];
}
free(methods);
return methodList;
}
類屬性的獲取
- (void)getIvarAndChange {
NSLog(@"修改前:%@", self.name);
unsigned int count = 0;
Ivar *members = class_copyIvarList([self class], &count);
for(int i = 0; i < count; i++) {
Ivar ivar = members[i];
const char *memberName = ivar_getName(ivar);
const char *memberType = ivar_getTypeEncoding(ivar);
//依次打印屬性名稱和屬性類型
NSLog(@"%s : %s", memberName, memberType);
if(strcmp(memberName, "_name") == 0) {
// 修改前
NSString *name = (NSString *)object_getIvar(self, members[i]);
NSLog(@"-name:%@", name);
// 修改后
object_setIvar(self, members[i], @"test");
NSString *nameReset = (NSString *)object_getIvar(self, members[i]);
NSLog(@"-nameReset:%@", nameReset);
break;
}
}
free(members);
NSLog(@"修改后:%@", self.name);
}
實例方法的獲取
- (void)getMethod {
unsigned int count;
Method *methods = class_copyMethodList([self class], &count);
for (int i = 0; i < count; i++) {
Method method = methods[i];
SEL selector = method_getName(method);
NSString *name = NSStringFromSelector(selector);
NSLog(@"實例方法:%@",name);
}
free(methods);
}
類方法的獲取
- (void)getClassMethod {
Class metaClass = object_getClass([self class]);
unsigned int count;
Method *classMethods = class_copyMethodList(metaClass, &count);
for (int i = 0; i < count; i++) {
Method classMethod = classMethods[i];
SEL selector = method_getName(classMethod);
NSString *name = NSStringFromSelector(selector);
NSLog(@"類方法:%@",name);
}
free(classMethods);
}