Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Objective c 如何创建对象遵循协议的NSMutableArray?_Objective C_Nsmutablearray_Protocols - Fatal编程技术网

Objective c 如何创建对象遵循协议的NSMutableArray?

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

如何创建对象遵循协议的NSMutableArray? 例如,在swift中,我可以执行以下操作:
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中相同的强泛型