Is it possible to add “keyed-subscripting” to Class objects?

后端 未结 1 1566
夕颜
夕颜 2021-01-13 02:21

In the vein of...

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

Is it also possible

相关标签:
1条回答
  • 2021-01-13 02:55

    Josh Caswell's comment pointed out the problem:

    You're using the type name. Try it with a class object in a variable. id myClass = [MyClass class]; myClass[@"document"]; Or [MyClass class][@"document"]

    I SWEAR I had tried that. BIBLE. But the proof is in the pudding...

    @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!)
    

    or for all my one-liner freaky-deaky's out there...

    x = ((id)MyClass.class)[@"document"] // "YEEHAW" 
    
    0 讨论(0)
提交回复
热议问题