为什么指针无法取回新值? iOS版

时间:2015-08-22 17:20:20

标签: ios function pointers uibutton

问题如下:

@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可以做到这一点,但指针无法取出新值?

非常感谢你的帮助!

2 个答案:

答案 0 :(得分:2)

当您声明andEqualToBtn:(UIButton *)button时,您获取指针的值,而不是对实际指针的引用。

如果您需要更改指针指向的内容,则需要andEqualToBtn:(UIButton **)button,然后修改您的参数和作业以进行匹配。

答案 1 :(得分:1)

如上所述,没有理由期待" log1"和" log5"与众不同。 btnbutton是两个独立的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;
}