在方法参数中指定对象的协议

时间:2021-12-24 21:34:08

I want to pass an object to a method which should conform to a protocol, and be able to call the methods which are defined that protocol. However, I can't find any way of doing so. For example:

我想将一个对象传递给一个符合协议的方法,并且能够调用定义该协议的方法。但是,我找不到任何这样做的方法。例如:

+ (void)prepareToBounceInView:(UIView*<PixelUI>)pixelUIView 
    fromEdge:(PixelUIViewBounceEdge)edge;

The first parameter of the method is a UIView subclass which should conform to the PixelUI protocol, and the method should then be able to access properties and call methods defined in the protocol.

该方法的第一个参数是一个UIView子类,它应该符合PixelUI协议,然后该方法应该能够访问协议中定义的属性和调用方法。

The only thing that worked was using id<PixelUI> as the type of the object, but then I can't access any of the properties or methods of the object itself, only those defined in the protocol; so I have to re-cast the object as (UIView*) when I need to treat it as the object it is, rather than as the delegate. This creates some ugly syntax, like this:

唯一有效的方法是使用id 作为对象的类型,但是我无法访问对象本身的任何属性或方法,只能访问协议中定义的属性或方法;因此,当我需要将对象视为对象时,我必须将对象重新转换为(UIView *),而不是作为委托。这会创建一些丑陋的语法,如下所示:

UIView *view = (UIView*)pixelUIView;
view.frame = pixelUIView.bounceBackFrame;

where view and pixelUIView are actually the same object, but have to be accessed using two different variable names.

其中view和pixelUIView实际上是同一个对象,但必须使用两个不同的变量名来访问。

If this is impossible then I will do as I have been doing and pass it in as id and then re-cast it. But if there is some syntax which will allow me to pass it in as its actual object while still specifying its protocol I'd love to know.

如果这是不可能的,那么我将按照我的方式做,并将其作为id传递,然后重新投射它。但是,如果有一些语法允许我将其作为实际对象传递,同时仍然指定其协议,我很乐意知道。

1 个解决方案

#1


2  

The order of the protocol and the star is important:

协议和明星的顺序很重要:

+ (void)prepareToBounceInView:(UIView<PixelUI> *)pixelUIView 
    fromEdge:(PixelUIViewBounceEdge)edge;

With this no casts should be necessary.

有了这个,不需要演员阵容。

#1


2  

The order of the protocol and the star is important:

协议和明星的顺序很重要:

+ (void)prepareToBounceInView:(UIView<PixelUI> *)pixelUIView 
    fromEdge:(PixelUIViewBounceEdge)edge;

With this no casts should be necessary.

有了这个,不需要演员阵容。