Objective c 如何创建对象遵循协议的NSMutableArray?
如何创建对象遵循协议的NSMutableArray? 例如,在swift中,我可以执行以下操作:Objective c 如何创建对象遵循协议的NSMutableArray?,objective-c,nsmutablearray,protocols,Objective C,Nsmutablearray,Protocols,如何创建对象遵循协议的NSMutableArray? 例如,在swift中,我可以执行以下操作: var数组:[MyProtocol]=[] 如何在objC中实现这一点在Objective-C中,您可以通过将协议类型的变量声明为id,例如: @protocol SomeProtocol<NSObject> ... @end @interface SomeClass : NSObject<SomeProtocol> // base class NSObject, impl
var数组:[MyProtocol]=[]
如何在objC中实现这一点在Objective-C中,您可以通过将协议类型的变量声明为
id
,例如:
@protocol SomeProtocol<NSObject>
...
@end
@interface SomeClass : NSObject<SomeProtocol> // base class NSObject, implements SomeProtocol
...
@end
@implementation SomeClass
...
@end
// a variable declaration somewhere which holds a reference to any object
// which implements SomeProtocol
id<SomeProtocol> anyObjectImplementingSomeProtocol = SomeClass.new;
@protocol-SomeProtocol
...
@结束
@接口SomeClass:NSObject//基类NSObject,实现SomeProtocol
...
@结束
@类的实现
...
@结束
//保存对任何对象的引用的变量声明
//它实现了一些协议
id anyObjectImplementingSomeProtocol=SomeClass.new;
使用Objective-C的轻量级泛型,您可以将其扩展到协议类型的容器,例如:
NSMutableArray<id<SomeProtocol>> someArray = NSMutableArray.new;
NSMutableArray someArray=NSMutableArray.new;
警告:轻量级泛型之所以命名,是因为它很容易绕过它们施加的限制,例如,通过将不实现SomeProtocol
的对象添加到someArray
。您不会得到与Swift中相同的强泛型
嗯