可以添加“键控下标”到类对象? [英] Is it possible to add "keyed-subscripting" to Class objects?

查看:107
本文介绍了可以添加“键控下标”到类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在...的静脉中...

In the vein of...

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

也可以下标 / code> objects?我也是,我想知道,与你..但认为我会发布这个问题,因为我测试了,自己...

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"];




错误:意外接口名称'MyClass':预期表达式

error: unexpected interface name 'MyClass': expected expression

但是为什么,Daddy? $ c>'如果你问我,请务必得到 NSObject 的短端。

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

推荐答案

Josh Caswell的评论指出了问题:


类型名称。尝试一个类对象在一个变量。 id myClass = [MyClass class]; myClass [@document]; [MyClass class] [@document]

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"]

我尝试过的SWEAR。 BIBLE 。但是证明是在布丁...

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

-liner freaky-deaky's 在那里...

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

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

这篇关于可以添加“键控下标”到类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆