Skip to content

Instantly share code, notes, and snippets.

Last active September 4, 2017 06:37
Show Gist options
  • Save 0xced/5107798 to your computer and use it in GitHub Desktop.
Save 0xced/5107798 to your computer and use it in GitHub Desktop.
NSObject category to get subclasses
#import <Foundation/Foundation.h>
@interface NSObject (Subclasses)
+ (NSSet *) subclasses_xcd;
#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];
objc_setAssociatedObject(self, SubclassesKey, subclasses, OBJC_ASSOCIATION_COPY);
return subclasses;
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment