1

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.

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:

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.

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.

1 Answer 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Aha! And I thought I'd tried every combination of type, protocol and asterisk ;) I've just gone through and changed the methods to use that syntax and I was indeed able to use both the protocol methods/properties and those of the object itself without casting. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.