Search code examples
objective-ciospointersselectorimp

ios how can i take a IMP to SEL


I define a function of point

typedef void (^ButtonClick)(id sender);

and i want to call it when Button click(UIButton addTarget to call ^ButtonClick function) but it is could find the pointer.

-(void)addRightButton:(UIImage*)btnImage click:(ButtonClick)click{
    UIButton *modalViewButton = [UIButton buttonWithType:UIButtonTypeCustom];

    [modalViewButton addTarget:self
      action:@selector(click) // <==== could not find pointer.Pointer errors
          forControlEvents:UIControlEventTouchUpInside];
    // other code to add modelViewButton on View.....
}

-(void)test
{ 
    [self addRightButton:[UIImage imageNamed:@"btn_shuaxin_1.png"] click:^(id sender) {
         NSLog(@"it is test code");//<===never called
    }];
}

how to make it to SEL?


Solution

  • You can't get selectors like this. (For getting selectors at runtime, use the sel_getUid() function). Also, you're confusing selectors and blocks. What you want is possible, but using a different approach:

    - (void)addRightButton:(UIImage *)btnImage click:(ButtonClick)click{
        UIButton *modalViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
    
        [modalViewButton addTarget:click
            action:@selector(invoke)
            forControlEvents:UIControlEventTouchUpInside];
    }
    
    - (void)test
    { 
        [self addRightButton:[UIImage imageNamed:@"btn_shuaxin_1.png"] click:^{
            NSLog(@"it is test code");
        }];
    }