问题
Is it possible to declare variable in @protocol? Just to force programmers to add those variable in implementing class's(classes which implements this protocol) header and implementation?
Thanks
回答1:
Short answer: No, it isn't possible to do that. You can enforce the availability of methods and properties at most.
回答2:
You can't declare ivars in @protocol
s but you can force the conforming class to implement an accessor and a mutator, which sounds like what you're getting at. For example:
@protocol Priced
@property(assign, nonatomic) double price;
@end
@interface Carrot : NSObject <Priced> {
double price;
}
@end
@implementation Carrot
@synthesize price;
@end
回答3:
You could make the objects a concrete subclass. That would be the only way to ensure that they contained the internals that you needed. Of course if you are interested in how the classes are storing their data internally... That is violating some oop paradigms.
来源:https://stackoverflow.com/questions/7315711/protocol-to-force-variable-declaration-objective-c