Last active
September 4, 2017 06:37
-
-
Save 0xced/5107798 to your computer and use it in GitHub Desktop.
NSObject category to get subclasses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
@interface NSObject (Subclasses) | |
+ (NSSet *) subclasses_xcd; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "NSObject+Subclasses.h" | |
#import <objc/runtime.h> | |
@implementation NSObject (Subclasses) | |
static inline BOOL IsSubclassOfClass(Class subclass, Class superclass) | |
{ | |
for (Class class = class_getSuperclass(subclass); class != Nil; class = class_getSuperclass(class)) | |
{ | |
if (class == superclass) | |
return YES; | |
} | |
return NO; | |
} | |
+ (NSSet *) subclasses_xcd | |
{ | |
static void * SubclassesKey = &SubclassesKey; | |
NSMutableSet *subclasses = objc_getAssociatedObject(self, SubclassesKey); | |
if (!subclasses) | |
{ | |
subclasses = [NSMutableSet set]; | |
unsigned int count = 0; | |
Class *classes = objc_copyClassList(&count); | |
for (int i = 0; i < count; i++) | |
{ | |
Class class = classes[i]; | |
// Do not use -[NSObject isSubclassOfClass:] in order to avoid calling +initialize on all classes | |
if (IsSubclassOfClass(class, self)) | |
[subclasses addObject:class]; | |
} | |
free(classes); | |
objc_setAssociatedObject(self, SubclassesKey, subclasses, OBJC_ASSOCIATION_COPY); | |
} | |
return subclasses; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, may i know if the licensing for the above piece of code? Are the code granted open source with no restriction to the rights of use, copy, merge, publish, distribute, sublicense and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.