开发者

Protocol to force variable declaration - Objective C

开发者 https://www.devze.com 2023-04-03 09:42 出处:网络
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?

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


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.

0

精彩评论

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

关注公众号