Skip to content

Commit d13f763

Browse files
committed
NSObject (QMUI) 增加方法用于遍历某个实例的所有方法
1 parent bb6ad48 commit d13f763

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

QMUIKit/UIKitExtensions/NSObject+QMUI.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,18 @@
3838
*/
3939
- (id)qmui_performSelectorToSuperclass:(SEL)aSelector withObject:(id)object;
4040

41+
/**
42+
使用 block 遍历当前实例的所有方法,父类的方法不包含在内
43+
*/
44+
- (void)qmui_enumrateInstanceMethodsUsingBlock:(void (^)(SEL selector))block;
45+
46+
/**
47+
使用 block 遍历指定的某个类的实例方法,该类的父类方法不包含在内
48+
* @param aClass 要遍历的某个类
49+
* @param block 遍历时使用的 block,参数为某一个方法
50+
*/
51+
+ (void)qmui_enumrateInstanceMethodsOfClass:(Class)aClass usingBlock:(void (^)(SEL selector))block;
52+
4153
/**
4254
遍历某个 protocol 里的所有方法
4355

QMUIKit/UIKitExtensions/NSObject+QMUI.m

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
#import "NSObject+QMUI.h"
1010
#import <objc/message.h>
11+
#import <objc/runtime.h>
1112

1213
@implementation NSObject (QMUI)
1314

@@ -48,6 +49,23 @@ - (id)qmui_performSelectorToSuperclass:(SEL)aSelector withObject:(id)object {
4849
return (*objc_superAllocTyped)(&mySuper, aSelector, object);
4950
}
5051

52+
- (void)qmui_enumrateInstanceMethodsUsingBlock:(void (^)(SEL))block {
53+
[NSObject qmui_enumrateInstanceMethodsOfClass:self.class usingBlock:block];
54+
}
55+
56+
+ (void)qmui_enumrateInstanceMethodsOfClass:(Class)aClass usingBlock:(void (^)(SEL selector))block {
57+
unsigned int methodCount = 0;
58+
Method *methods = class_copyMethodList(aClass, &methodCount);
59+
60+
for (unsigned int i = 0; i < methodCount; i++) {
61+
Method method = methods[i];
62+
SEL selector = method_getName(method);
63+
if (block) block(selector);
64+
}
65+
66+
free(methods);
67+
}
68+
5169
+ (void)qmui_enumerateProtocolMethods:(Protocol *)protocol usingBlock:(void (^)(SEL))block {
5270
unsigned int methodCount = 0;
5371
struct objc_method_description *methods = protocol_copyMethodDescriptionList(protocol, NO, YES, &methodCount);

0 commit comments

Comments
 (0)