问题如下:
@property(nonatomic,strong)UIButton *startBtn;
-(void)createView
{
int btnW = 22;
int btnH = 14;
self.startBtn = [[UIButton alloc] init];
NSLog(@"%@",self.startBtn);//log1
[self createButton:@selector(startBtnDidClicked:) frame:CGRectMake( screenW - btnW , screenH/2 - btnH, btnW, btnH) addedto:self.view andEqualToBtn:self.startBtn];
//quetion is here
NSLog(@"%@",self.startBtn);//log5 --same as log1 (the expected value should be different from log1)
}
- (void)createButton:(SEL)action frame:(CGRect)frame addedto:(UIView *)parentView andEqualToBtn:(UIButton *)button
{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
NSLog(@"%@",btn); //log2
button = btn;
NSLog(@"%@",button); // log3 --same as log2
NSLog(@"%@",self.startBtn); //log4 -- same as log1
[button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[parentView addSubview:button];
}
我想取回值,所以预期的结果应该是:log5应该与log1不同,和log2相同。我徘徊为什么log3可以做到这一点,但指针无法取出新值?
非常感谢你的帮助!
答案 0 :(得分:2)
当您声明andEqualToBtn:(UIButton *)button
时,您获取指针的值,而不是对实际指针的引用。
如果您需要更改指针指向的内容,则需要andEqualToBtn:(UIButton **)button
,然后修改您的参数和作业以进行匹配。
答案 1 :(得分:1)
如上所述,没有理由期待" log1"和" log5"与众不同。 btn
和button
是两个独立的UIButton
个实例。 button
等于self.startBtn
。
我建议您将代码重新组织为:
-(void)createView
{
int btnW = 22;
int btnH = 14;
self.startBtn = [self createButton:@selector(startBtnDidClicked:) frame:CGRectMake( screenW - btnW , screenH/2 - btnH, btnW, btnH) addedto:self.view];
}
- (UIButton *)createButton:(SEL)action frame:(CGRect)frame addedto:(UIView *)parentView
{
UIButton *btn = [[UIButton alloc] initWithFrame:frame];
[btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
[parentView addSubview:btn];
return btn;
}