-2

I'd like to do something like this:

.h

LocalRoom* zone1;
LocalRoom* zone2;
LocalRoom* zone3;
LocalRoom* zone4;
etc....

.m

NSString *number = 1;
NSString *variable = [NSString stringWithFormat: @"zone%@", number]
[[variable variableValue] broadcastChatMessage:redStringPrefix fromUser:@"server"];

emulating:

[zone1 broadcastChatMessage:redStringPrefix fromUser:@"server"];

How do I do this? Is it possible?

8
  • Why don't you use an NSMutableDictionary if you need named values? Commented Dec 25, 2012 at 18:18
  • Or you can use obj-c/runtime.... Commented Dec 25, 2012 at 18:19
  • Creating variables at runtime. Commented Dec 25, 2012 at 18:20
  • 1
    You could do what @AnoopVaidya is suggesting, but it isn't really practical or readable compared to just using a mutable dictionary. Associated objects would work, for example. Commented Dec 25, 2012 at 18:21
  • 1
    that is why my first reply was dict and second one obj-c runtime :) Commented Dec 25, 2012 at 18:22

3 Answers 3

6

Given names like “zone1”, “zone2”, etc., I would make an array rather than a dictionary. Either way, these should not be separate variables.

Sign up to request clarification or add additional context in comments.

Comments

3
 @property(strong) NSMutableDictionary *zones;

 -(id)init {
   ....
   _zones = [[NSMutableDictionary alloc] init];
   ....
 }

 aZone = [_zones objectForKey: [NSString stringWithFormat:@"zone%d", someZoneNumber]];

... etc ...

Comments

3

You can do something similar using Key-Value Coding. You would write

[[self valueForKey:variable] broadcastChatMessage:redStringPrefix fromUser:@"server"];

rather than

[[variable variableValue] broadcastChatMessage:redStringPrefix fromUser:@"server"];

This would of course require that zone1, zone2, etc. are instance variables (or properties) on self.

1 Comment

This'll work, but I'd suggest against KVC vs. just using an NSMutableDictionary.

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.