【问题标题】:Pass Button object to method将 Button 对象传递给方法
【发布时间】:2011-09-27 01:12:58
【问题描述】:

我正在尝试编写一个通用方法,它允许我传递以下内容:“x”、“y”、“object”,然后让它移动。目前我有这个:

 -(void) changeObjectLocations: (integer_t) xSpot: (integer_t) ySpot: (id) sender   {

  if (![sender isKindOfClass:[UIButton class]])
   {
       UIButton *myObject = (UIButton *)sender;
       [UIView animateWithDuration:1.5              
        animations:^{                
        CGRect newFrame = myObject.frame;
        newFrame.origin.x = xSpot;
        newFrame.origin.y = ySpot;
        myObject.frame = newFrame;
    }];             
}
  else if (![sender isKindOfClass:[UILabel class]])
  {
    UILabel *myObject = (UILabel *)sender;
    [UIView animateWithDuration:1.5  animations:^{                
        CGRect newFrame = myObject.frame;
        newFrame.origin.x = xSpot;
        newFrame.origin.y = ySpot;
        myObject.frame = newFrame;
    }];  
  }
}

然后我想这样称呼它:

-(void) orientationBlockLandscape {

    [self changeObjectLocations: 456 :282 : btn1] ;
    [self changeObjectLocations: 391 :227 : lblTitle] ;

}

虽然它正在工作,但在编译时我收到以下警告:

SecondViewController.m:33:警告:“SecondViewController”可能不会响应“-changeObjectLocations:::”

有没有更好的方法可以/应该传递对象?提前感谢您提供的所有帮助。

地理...

【问题讨论】:

    标签: objective-c xcode ipad ios4


    【解决方案1】:

    根据输出的警告,听起来您没有在 SecondViewController 的标头中定义 changeObjectLocations - 或者它与您实现的签名不同。

    【讨论】:

    • 就是这样。 Objective-C 的新手,所以我总是忘记一些事情!谢谢
    • @没问题。顺便说一句,好名字! ;)
    【解决方案2】:

    编译器查找选择器,这些选择器是删除了变量和返回的方法定义。

    这样的方法:

    -(void) setObject:(id) anObject forKey:(NSString *) keyname;
    

    ... 会有一个选择器:

    setObject:forKey:
    

    因此,您的方法:

     -(void) changeObjectLocations: (integer_t) xSpot: (integer_t) ySpot: (id) sender
    

    ... 将有一个选择器:

    changeObjectLocations:xSpot:ySpot:
    

    请注意,参数名称是选择器的一部分,因此:

    changeObjectLocations:xSpot:ySpot:
    

    changeObjectLocations:::
    

    .. 是两个完全独立的选择器,代表两个完全独立的方法。

    虽然在语言中使用不带名称的参数是合法的,例如":::" 这是非常非常糟糕的做法,主要是因为它很容易发生命名冲突。显式不仅使代码更易于阅读和维护,而且使编译器和运行时更容易运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-05
      • 2019-03-22
      相关资源
      最近更新 更多