Reputation: 31
How to create NSMutableArray in which objects follow protocol?
For example in swift I can do something like:
var array:[MyProtocol] = []
How to implement that in objC
Upvotes: 0
Views: 199
Reputation: 53000
In Objective-C you declare a variable of protocol type by declaring it as id<SomeProtocol>
, e.g.:
@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;
Using Objective-C's lightweight generics you can extend this to containers of protocol type, e.g.:
NSMutableArray<id<SomeProtocol>> someArray = NSMutableArray.new;
Warning: Lightweight generics are named that for a reason, it is quite easy to bypass the restrictions imposed by them, e.g. by adding an object which does not implement SomeProtocol
to someArray
. You don't get the same strong generics as in Swift.
HTH
Upvotes: 1