0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.