【问题标题】:Using performSelector:withObject:afterDelay: with non-object parameters使用 performSelector:withObject:afterDelay: 与非对象参数
【发布时间】:2011-03-06 13:21:32
【问题描述】:

我想在表格视图上调用setEditing:animated: 并稍有延迟。通常,我会使用 performSelector:withObject:afterDelay: 但是

  1. pSwOaD 只接受一个参数
  2. setEditing:animated: 的第二个参数是原始 BOOL - 不是对象

过去我会在自己的类中创建一个虚拟方法,例如setTableAnimated,然后调用[self performSelector:@selector(setTableAnimated) withObject:nil afterDelay:0.1f,但这对我来说感觉很笨拙。

有没有更好的方法?

【问题讨论】:

    标签: iphone objective-c cocoa


    【解决方案1】:

    为什么不使用 dispatch_queue ?

      double delayInSeconds = 2.0;
      dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
      dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
          [tableView setEditing …];
      });
    

    【讨论】:

    • 我不知道为什么这被否决了,这对我来说似乎是一个很好的解决方案。
    • 如果您使用的是 iOS4,这就是这样做的方法
    【解决方案2】:

    你需要使用NSInvocation:

    请参阅此代码,取自 answer,我已对其稍作更改以匹配您的问题:

    BOOL yes = YES;
    NSInvocation *inv = [NSInvocation invocationWithMethodSignature:[self.tableView methodSignatureForSelector:@selector(setEditing:Animated:)]];
    [inv setSelector:@selector(setEditing:Animated:)];
    [inv setTarget:self.tableView];
    [inv setArgument:&yes atIndex:2]; //this is the editing BOOL (0 and 1 are explained in the link above)
    [inv setArgument:&yes atIndex:3]; //this is the animated BOOL
    [inv performSelector:@selector(invoke) withObject:nil afterDelay:0.1f];
    

    【讨论】:

    • 我认为使用像 BOOL _yes = YES 这样的 var 名称会更清楚一些,因为它可以缓解您是否有错字(是与是)的一些困惑。
    • 另外只是想指出,使用YES的变量而不是直接传递bool的原因:NSInvocation抛出异常:[NSInvocation setArgument:atIndex:]: NULL address argumentexplained in this answer。跨度>
    【解决方案3】:

    选择器setEditing:animated:performSelector:withObject:afterDelay 不兼容。您只能调用具有 0 或 1 个参数的方法,并且参数(如果有)必须是一个对象。所以你的解决方法是要走的路。您可以将 BOOL 值包装在 NSValue 对象中并将其传递给您的 setTableAnimated 方法。

    【讨论】:

      【解决方案4】:

      如果您能理解它,请使用 NSInvocation 抓取器来创建调用对象并延迟调用它,使用 1 行而不是多行:http://overooped.com/post/913725384/nsinvocation

      【讨论】:

      • 如果涉及创建类,几乎没有一行。
      猜你喜欢
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 1970-01-01
      • 2022-09-28
      • 1970-01-01
      • 2014-03-09
      • 1970-01-01
      相关资源
      最近更新 更多