Can I pass a block as a @selector with Objective-C?

前端 未结 9 531
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 17:04

Is it possible to pass an Objective-C block for the @selector argument in a UIButton? i.e., Is there any way to get the following to work?

相关标签:
9条回答
  • 2020-11-30 17:59

    Doesn't it work to have an NSBlockOperation (iOS SDK +5). This code uses ARC and it is a simplification of an App I am testing this with (seems to work, at least apparently, not sure if I am leaking memory).

    NSBlockOperation *blockOp;
    UIView *testView; 
    
    -(void) createTestView{
        UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, 1024, 688)];
        testView.backgroundColor = [UIColor blueColor];
        [self.view addSubview:testView];            
    
        UIButton *btnBack = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [btnBack setFrame:CGRectMake(200, 200, 200, 70)];
        [btnBack.titleLabel setText:@"Back"];
        [testView addSubview:btnBack];
    
        blockOp = [NSBlockOperation blockOperationWithBlock:^{
            [testView removeFromSuperview];
        }];
    
        [btnBack addTarget:blockOp action:@selector(start) forControlEvents:UIControlEventTouchUpInside];
    }
    

    Of course, I am not sure how good this is for real usage. You need to keep a reference to the NSBlockOperation alive or I think that ARC will kill it.

    0 讨论(0)
  • 2020-11-30 18:04

    The library BlocksKit on Github (also available as a CocoaPod) has this feature built-in.

    Take a look at the header file for UIControl+BlocksKit.h. They've implemented Dave DeLong's idea so you don't have to. Some documentation is here.

    0 讨论(0)
  • 2020-11-30 18:06

    No, selectors and blocks are not compatible types in Objective-C (in fact, they're very different things). You'll have to write your own method and pass its selector instead.

    0 讨论(0)
提交回复
热议问题