简体   繁体   English

方法声明协议?

[英]Protocol on method declaration?

I'm starting to use the Nimbus framework and I just ran across this syntax for the first time. 我开始使用Nimbus框架,并且第一次遇到这种语法。 It looks like they are using some kind of protocol in the method declaration and then when declaring a variable. 看起来他们在方法声明中然后在声明变量时使用某种协议。 I've only seen protocols used in the header file right after the class name so this is completely new to me. 我仅在类名之后看到头文件中使用的协议,因此这对我来说是全新的。

- (UIView<NIPagingScrollViewPage>*)pagingScrollView:(NIPagingScrollView *)pagingScrollView pageViewForIndex:(NSInteger)pageIndex {

Also: 也:

UIView<NIPagingScrollViewPage>* pageView = nil;

What exactly does this mean? 这到底是什么意思? Why are they using this format? 他们为什么使用这种格式?

That declaration makes sure that the UIView returned conforms to the NIPagingScrollViewPage protocol. 该声明确保返回的UIView符合NIPagingScrollViewPage协议。 The compiler will emit a warning if the method tries to return an object that isn't declared to conform. 如果方法尝试返回未声明符合的对象,则编译器将发出警告。

A more common usage of that syntax would be a delegate, as you'll allow any class that conforms to the protocol to be the delegate, so that syntax is used to make sure the class conforms to the protocol. 该语法的更常见用法是委托,因为您将允许所有符合协议的类都作为委托,因此可以使用语法来确保该类符合协议。

-(void)setDelegate:(id<SampleDelegate>)del //Makes sure that del conforms to the protocol SampleDelegate, the compiler will emit a warning

This is just the way to declare that it is confirming to that protocol. 这只是声明它正在对该协议进行确认的方式。 Otherwise warnings will be shown. 否则将显示警告。 Then you have to use id. 然后,您必须使用id。

So It is always a good practice to use (datatype<protocol>*)variableName 因此,使用(datatype<protocol>*)variableName始终是一个好习惯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM