Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 protocol) header and implementation?

Thanks

like image 870
TeaCupApp Avatar asked Dec 13 '22 09:12

TeaCupApp


2 Answers

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

like image 172
Rudy Velthuis Avatar answered Jan 02 '23 13:01

Rudy Velthuis


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
like image 28
Tom Dalling Avatar answered Jan 02 '23 11:01

Tom Dalling