Obj-C:类符合协议作为参数 [英] Obj-C: Class conform to protocol as parameter

查看:104
本文介绍了Obj-C:类符合协议作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在目标c中,可以将类作为参数传递给方法:

   - (void)methodThatTakesClass :(类)theClass; 

并且可以传递符合协议的实例作为参数:

   - (void)myConformInstance:(id< MyProtocol>)theObject; 

是否可以使用组合功能。

解决方案

/ div>

是的。下面是一个有效的程序,它将记录NSObject类。

  #import< Foundation / Foundation.h> 
void f(Class< NSObject> c){
NSLog(@%@,c);
}
int main(){
f([NSObject class]);
}

这将导致编译器错误,如果你试图传递一个类, t符合NSObject,如 Object 类。您还可以将其用于方法。

   - (void)printClass:(Class< NSObject>)c; 


In objective c it is possible to pass a class as parameter to a method:

- (void) methodThatTakesClass:(Class)theClass;

And it is possible to pass an instance that is conform to an protocol as parameter:

- (void) myConformInstance:(id <MyProtocol>)theObject;

Is it possible to use the combined functionality. A method which takes a class which is conform to a certain protocol.

Thanks.

解决方案

Yes. The following is a valid program which will log the NSObject class.

#import <Foundation/Foundation.h>
void f(Class <NSObject> c) {
    NSLog(@"%@",c);
}
int main() {
    f([NSObject class]);
}

This would cause a compiler error if you tried to pass a class which doesn't conform to NSObject, such as the Object class. You can also use it for methods.

- (void)printClass:(Class <NSObject>)c;

这篇关于Obj-C:类符合协议作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆