Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a category to an Objective-C meta-class?

I would assume... NO. But wouldn't it be nice if instead of...

NSStringFromClass(SomeClass)

you could...

@interface      Class (ToString)
@property (readonly) NSString* stringValue;
@end
@implementation Class (ToString)
- (NSString*) stringValue { return NSStringFromClass(self); }
@end

and subsequently use...

SomeClass.stringValue

I'm sure there's a good reason the meta-heirarchy prevents this (although it seems like a half-truth when it's said that Classes (and Protocols, and Methods, etc) are-indeed "real" Objects)... when a lot of the "stuff" that makes a NSObject an Object can NOT be performed on a "metaclass".

Can anyone shed a light on this functional difference / offer an alternative (i.e. resolveClassMethod: that might achieve similar result?

like image 657
Alex Gray Avatar asked Jan 28 '26 03:01

Alex Gray


1 Answers

Since an instance method of a metaclass is just a class method on the non-meta class, why not simply add a category on the original (non-meta) class?

@implementation NSObject (Name)

+ (NSString *)className
{
    return NSStringFromClass(self);
}

@end

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!