开发者

Can I have a protocol as a class variable in Objective-C?

开发者 https://www.devze.com 2023-03-15 20:17 出处:网络
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:

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 OtherC开发者_C百科lass: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?


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.


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消