Segev
Segev

Reputation: 19303

How to convert a number to its enum?

I've declared an enum like so:

typedef enum
{
    firstView = 1,
    secondView,
    thirdView,
    fourthView
}myViews

My goal is that a UIButton will trigger another function with the uiButton sender.tagand that function will know to convert the integer to the correct view. I'm aware that I can just create an array with the names of the views but I am looking for something smarter than that using the declared enum.

Example:

-(void)function:(UIButton *)sender
{
  ...
  ...
  NSLog(@"current View: %@",**converted view name from sender.tag);
}

Thanks

Upvotes: 0

Views: 1730

Answers (3)

Sulthan
Sulthan

Reputation: 130072

Well, the best solution is to actually store the views. You can also use a IBOutletCollection to create the array. Declaring an enum is just another way to store names.

self.views = @[firstView, secondView, thirdView, forthView];

...

button.tag = [self.views indexOfObject:firstView];

...

- (void)buttonTappedEvent:(UIButton*)sender {
    UIView* view = [self.views objectAtIndex:sender.tag];
}

PS: converting tag into enum is trivial, it's just myViews viewName = sender.tag, possibly with a cast myViews viewName = (myViews) sender.tag

Upvotes: 3

andykkt
andykkt

Reputation: 1706

What I normally do is declare it to dictionary for once using dispatch once

static NSDictionary* viewList = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
        viewList = [NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:1], @"firstView",[NSNumber numberWithInt:2], @"secondView",[NSNumber numberWithInt:2], @"thirdView",@"secondView",[NSNumber numberWithInt:3], @"fourthView",
nil];
    });

and find with tag like this:

-(void)function:(UIButton *)sender
{
  NSLog(@"current View: %@",[viewList objectForKey:[NSNumber numberWithInt:sender.tag]);
}

Upvotes: 0

Zhang
Zhang

Reputation: 11607

How about storing it inside a NSMutableDictionary ?

NSMutableDictionary *viewList = [[NSMutableDictionary alloc] init];

for(int i = 1; i <= 4; i++)
{
    [viewList setObject:@"firstView" forKey:[NSString stringWithFormat:@"%d", i]];
}

...

-(void)buttonTappedEvent:(id)sender
{
    UIButton *tappedButton = (UIButton *)sender;

    NSLog(@"current view: %@", [viewList objectForKey:[NSString stringWithFormat:"%d", tappedButton.tag]]);
}

Upvotes: 0

Related Questions