Protocol to force variable declaration - Objective C
Is it possible to declare variable in @protocol? Just to force programmers to add those variable in implementing class's(classes which implements this pro开发者_C百科tocol) header and implementation?
Thanks
Short answer: No, it isn't possible to do that. You can enforce the availability of methods and properties at most.
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
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.
精彩评论