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

。_饼干妹妹 提交于 2019-12-30 10:07:12

问题


In the vein of...

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

Is it also possible to "subscript" Class objects? I too, am about to find out, with you.. but thought I would post this question as I tested it out, myself...

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

And alas.. it is not...

id x = MyClass[@"document"];

error: unexpected interface name 'MyClass': expected expression

But why, Daddy? Class' sure get the short end of NSObject's stick, if you ask me.


回答1:


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" 


来源:https://stackoverflow.com/questions/23440600/is-it-possible-to-add-keyed-subscripting-to-class-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!