4

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

TeaCupApp
  • 11,316
  • 18
  • 70
  • 150

3 Answers3

9

Short answer: No, it isn't possible to do that. You can enforce the availability of methods and properties at most.

Rudy Velthuis
  • 28,387
  • 5
  • 46
  • 94
  • Thank you Rudy, This was just a thought. As I was implementing a really weird design paradigm. Any work around? – TeaCupApp Sep 06 '11 at 06:36
  • 2
    You shouldn't care what instance variables objects happen to use. Declare the property and let classes that implement the protocol get and set it however they want. – Tommy Sep 06 '11 at 06:39
  • No workaround. I don't know of anything that can force the presence of a certain instance variable. Try to use a property as replacement. – Rudy Velthuis Sep 06 '11 at 13:23
3

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
Tom Dalling
  • 23,305
  • 6
  • 62
  • 80
  • yeah I was aware of having methods A.K.A. behaviour. But thought of forcing programmers to add a must variable. Thanks – TeaCupApp Sep 06 '11 at 06:51
1

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.

Grady Player
  • 14,399
  • 2
  • 48
  • 76
  • +1 although subclassing (user) classes seems to be much rarer in Objective-C than (say) C++, `@protocol` may not be the right tool for the OP's needs. – Ephemera Apr 20 '14 at 09:43
  • I tend to make subclasses pretty often... I think that lots of cocoa / iOS programmers use the tools that they are familiar with, which is understandable... given than C++ and Java have been taught in colleges along with OOP for ~20 years... – Grady Player Apr 20 '14 at 19:35