Protocol to force variable declaration - Objective C

自古美人都是妖i 提交于 2020-01-03 17:47:08

问题


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 @protocols 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!