Can I add signature-key classes to objects?

In the spirit of ...

@implementation MyClass
- (id) objectForKeyedSubscript:(id)k { 
       return [self something:k]; 
}

Is it also possible to "index" Classobjects? I am also going to find out with you .. but thought that I would post this question when I checked it myself ...

+ (id) objectForKeyedSubscript:(id)k { 
       return [self.shared something:k]; 
}

And alas .. it's not ...

id x = MyClass[@"document"];

error: unexpected interface name "MyClass": expected expression

But why, dad? Class' NSObjectBe sure to get the short end of the stick if you ask me.

+4
source share
1 answer

Josh Caswell's comment pointed to the problem:

. . id myClass = [MyClass class]; myClass[@"document"]; [MyClass class][@"document"]

SWEAR . . ...

@interface MyClass : NSObject
@property (readonly) id  boring;
@end
@implementation MyClass
- boring   { return @"typical"; }
+ document { return  @"YEEHAW"; }
- objectForKeyedSubscript:key { return [self valueForKey:key]; }
+ objectForKeyedSubscript:key { 
  return [self performSelector:NSSelectorFromString(key)]; 
}
@end

...

id a = MyClass.new;
id x = a[@"boring"];   // "typical" (via "normal" keyed subscription)
id b = MyClass.class;
   x = z[@"document"]; // "YEEHAW" (via CLASS keyed-subscript!)

freaky-deaky's ...

x = ((id)MyClass.class)[@"document"] // "YEEHAW" 
+3

Source: https://habr.com/ru/post/1539088/


All Articles