简体   繁体   中英

why the custom class could not successfully call its own class method? iOS

Codes are as follows:

In the myViewController.m file :

A.This one could work(instance method)

 -(UIButton *)createButton:(SEL)action addedto:(UIView *)fatherView
 { 
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];

    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];

    [fatherView addSubview:btn];
    return btn;
}

-(void)startBtnDidClicked:(UIButton *)startBtn
{
    NSLog(@"start!");
}

-(void)viewDidLoad
{
    self.startBtn = [self createButton:@selector(startBtnDidClicked:)  addedto:self.parentViewController.view  ];
}

B.But this one could not work(class method) :[error:when trigger the "startBtnDidClicked:",it shows error like:" unrecognized selector sent to xxxx "]

  + (UIButton *)createButton:(SEL)action addedto:(UIView *)fatherView
{ 
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];

    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];

    [fatherView addSubview:btn];
    return btn;
}

-(void)startBtnDidClicked:(UIButton *)startBtn
{
    NSLog(@"start!");
}

-(void)viewDidLoad
{
    self.startBtn = [[self class] createButton:@selector(startBtnDidClicked:)  addedto:self.parentViewController.view  ];
}

In the class method createButton:added: (in your 2nd bit of code), self is a reference to the class, not the instance of the class. So your button is looking for a class method named startBtnDidClicked: , not an instance method named startBtnDidClicked: .

If you want to use a class method to create the button, you need to add another parameter for the target instead of assuming self .

+ (UIButton *)createButton:(id)target action:(SEL)action addedto:(UIView *)fatherView
{ 
    UIButton *btn = [[UIButton alloc] initWithFrame:frame];

    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];

    [fatherView addSubview:btn];
    return btn;
}

-(void)startBtnDidClicked:(UIButton *)startBtn
{
    NSLog(@"start!");
}

-(void)viewDidLoad
{
    self.startBtn = [[self class] createButton:self action:@selector(startBtnDidClicked:) addedto:self.parentViewController.view  ];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM