簡體   English   中英

為什么自定義類無法成功調用其自己的類方法? 的iOS

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

代碼如下:

myViewController.m文件中

答:這可以工作(實例方法)

 -(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.但是,這不能正常工作(類方法) :[錯誤:當觸發“ startBtnDidClicked:”時,它顯示如下錯誤:“ 無法識別的選擇器發送給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  ];
}

在類方法createButton:added:在您的代碼的第2位)中, self是對類的引用,而不是類的實例。 因此,您的按鈕正在尋找一個名為startBtnDidClicked:的類方法,而不是一個名為startBtnDidClicked:的實例方法。

如果要使用類方法創建按鈕,則需要為目標添加另一個參數,而不是假設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  ];
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM