如何将数字转换为枚举?

时间:2013-05-26 13:47:16

标签: ios objective-c cocoa-touch cocoa

我已经宣布了这样的枚举:

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

我的目标是UIButton将触发uiButton sender.tag的另一个函数,该函数将知道将整数转换为正确的视图。我知道我可以创建一个包含视图名称的数组,但我正在寻找比使用声明的枚举更聪明的东西。

示例:

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

由于

3 个答案:

答案 0 :(得分:3)

嗯,最好的解决方案是实际存储视图。您还可以使用IBOutletCollection来创建阵列。声明enum只是存储名称的另一种方式。

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

...

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

...

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

PS:将tag转换为enum是微不足道的,只是 myViews viewName = sender.tag,可能有演员myViews viewName = (myViews) sender.tag

答案 1 :(得分:0)

如何将其存储在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]]);
}

答案 2 :(得分:0)

我通常做的是使用一次调度将其声明为字典一次

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];
    });

并找到像这样的标签:

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