[英]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.