作者:shajc220 | 来源:互联网 | 2023-12-12 18:36
本文介绍了如何在方法参数中指定一个对象的协议,以及如何调用符合该协议的方法。以一个具体的示例说明了如何在方法参数中指定一个UIView子类对象,并且该对象需要符合PixelUI协议,同时方法需要能够访问该对象的属性。
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*)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
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 个解决方案