2

I'm new to Objective C. I'm trying to use a protocol as I would an interface in Java, but I don't know how or even if it's the right tool for the job. I have defined a protocol in Protocol.h:

@protocol SomeProtocol
- (void)someMethod;
@end

Now, in another class, I need a variable that has someMethod

#import "Protocol.h"
@interface OtherClass:NSObject {
    SomeProtocol objWithSomeMethod;
}
@end

Of course "SomeProtocol objWithSomeMethod" gives me an error. So is there a way to declare an object that, regardless of type, conforms to this protocol?

3 Answers 3

4

Yes, use the angle brackets. You can declare an instance variable to conform to a protocol like this:

id<SomeProtocol> objWithSomeMethod;

If you want it to conform to more than one protocol, you use commas to separate them like this:

id<SomeProtocol, SomeOtherProtocol> objWithSomeMethod;

You can also declare variables or parameters the same way.

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

Comments

4

Angle brackets qualify objects as implementing protocols. In your example, write

#import "Protocol.h"
@interface OtherClass : NSObject {
    id<SomeProtocol> objWithSomeMethod;
}
@end

If you want to declare that a class implements an interface, you use the same notation, essentially:

@interface MyProtocolClass : NSObject <SomeProtocol> {
    // ...
}
@end

Comments

-1

You should declare your instance variable with his type, then the list of protocols inside <> and finally the variable name. So in your case, it would be:

#import "Protocol.h"
@interface OtherClass:NSObject {
    id <SomeProtocol> objWithSomeMethod;
}
@end

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.