【问题标题】:use an static function from a protocol in a function, objective-c在函数中使用协议中的静态函数,objective-c
【发布时间】:2011-10-28 01:34:20
【问题描述】:

我想在函数中使用协议中的静态函数:

    @implementation IPadPanoramaViewController
    - (void)viewDidLoad
    {
     [self.view addSubview:[PanoramaContent getPanoramaContentByPanoramaItem:[[PanoramaListItem alloc] init]]; 
     [super viewDidLoad];
}
@end

        @protocol PanoramaItemProtocol

        + (UIView *) getPanoramaItemBySection;

        @end


        @implementation PanoramaContent
    + (UIView *) getPanoramaContentByPanoramaItem:(id<PanoramaItemProtocol>) itemKind {

                return [itemKind getPanoramaItemBySection]; //here is the problem "unrecognized selector sent to instance"
        }
    @end

我希望“PanoramaListItem”不是 NSObject

【问题讨论】:

  • 什么是“PanoramaListItem”?您没有在示例代码中使用它。

标签: objective-c ios function inheritance protocols


【解决方案1】:

问题在于,当您在实例上调用 getPanoramaBySection 时,您已将其定义为类方法。在协议声明中,将+ 替换为-

【讨论】:

    【解决方案2】:

    首先,静态方法只能发送到一个类。如果不想创建对象,getPanoramaContentByPanoramaItem: 的参数应该是 Class 类型。您可以使用以下内容:

     + (UIView *) getPanoramaContentByPanoramaItem:(Class)itemKind {
         UIView *v = nil;
         if( [itemKind respondsToSelector:@selector(getPanoramaItemBySection)] ) {
             v = [itemKind getPanoramaItemBySection];
         }
         return v;
     }
    

    并发送消息:

    [self.view addSubview:[PanoramaContent getPanoramaContentByPanoramaItem:[PanoramaListItem class]]];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 2012-01-03
      • 2014-12-15
      • 1970-01-01
      • 2013-12-20
      • 2011-07-16
      相关资源
      最近更新 更多