【问题标题】:How to convert a number to its enum?如何将数字转换为其枚举?
【发布时间】:2013-05-26 13:47:16
【问题描述】:

我已经像这样声明了一个枚举:

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

谢谢

【问题讨论】:

    标签: ios objective-c cocoa-touch cocoa


    【解决方案1】:

    嗯,最好的解决方案是实际存储视图。您还可以使用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

    【讨论】:

    • 我刚刚看到您提供的解决方案与我最终采用的解决方案相同。一个问题,myViews viewName = (myViews) sender.tag; NSLog(@"View #: %u",viewName); 将输出一个数字而不是枚举名称
    • @EXEC_BAD_ACCESS 真。枚举只是一个符号名称。如果你写int a = 1; NSLog(@"%d", a),你不会期望它输出a。如果要记录描述性名称,则必须将枚举值转换为字符串。有不同的方法可以做到这一点 - 例如用名称或 X 宏声明第二个数组。在大多数情况下,整数就足够了,因为您知道它的含义。
    【解决方案2】:

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

    【讨论】:

    • “我知道我可以使用视图名称创建一个数组,但我正在寻找比使用声明的枚举更智能的东西。”
    • 枚举显然仅适用于序数类型:stackoverflow.com/questions/1851567/…。你的最终目标是什么,你想用视图和枚举来实现什么?在 iPhone 屏幕上按特定顺序动态加载视图?
    • 比这复杂一点。看起来数组是我唯一的选择。
    【解决方案3】:

    我通常做的是使用 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];
        });
    

    然后找到这样的标签:

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

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 1970-01-01
      • 2019-03-04
      • 2019-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      相关资源
      最近更新 更多