6

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.

4
  • I'd suggest create global pointer at shared instance if you don't want write long code MyClass.shared[@"document"]; Commented May 3, 2014 at 6:01
  • 2
    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"]. Commented May 3, 2014 at 16:17
  • Okay, I just grasped why you think that should work -- the subscript is turned into a message send, and the class name is valid as the reciever of a message send. It wouldn't surprise me, though, that the parser will only accept a literal message send (or the dot syntax). Commented May 3, 2014 at 16:25
  • @Cy-4AH My current approach is to usually just create C functions that do roughly the same as you suggest.. id MyClassReaper(NSString *str) { return objc_msgSend(MyClass.class, NSSelectorFromString(str)); }, etc... Again, these examples are only illustrative. Commented May 3, 2014 at 19:13

1 Answer 1

5

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" 
Sign up to request clarification or add additional context in comments.

2 Comments

+1 to both question and answer for humorous language interspersed with concise writing.
I believe by z you meant b, or vice versa.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.