Besi
Besi

Reputation: 22939

Define @property in Protocol

I have a number of UIViewController subclasses and I want them to share the same property called session which handles a "is logged in" state.

I know that I could use a parent class but this is very explicit and so I was wondering if I could "enforce" the session property via a shared protocol.

I have never seen an explicit property defined in a protocol (obviously you could define the setter and getter), so is defining a property inside a protocol an advisable pattern?

Upvotes: 5

Views: 4100

Answers (4)

Tom Tharakan
Tom Tharakan

Reputation: 21

In .h file:

 @property(nonatomic,strong)UILabel *mylabel;

In .m file:

 @synthesize mylabel = _mylabel;

compiler will create getter and setter for mylabel.

Ex -> 

-(void)setMylabe:(UILabel *) mylabel { //setter


}

-(UIlabel*)mylabel { // getter


}

Upvotes: 2

mAu
mAu

Reputation: 2018

@property can also appear in the declaration of a protocol or category.

Stated in the official apple documentation. So no problem there.

Upvotes: 11

user529758
user529758

Reputation:

Yes, using a protocol it's possible to add a property:

@protocol MyProtocol <NSObject>

@property (nonatomic, retain) NSFoobar *baz;

@end

And @synthesize baz; in every class that adopts this protocol (or you can mark the declared property as optional using the @optional keyword).

Upvotes: 4

jweyrich
jweyrich

Reputation: 32240

You can have properties in a protocol, provided every class that conforms to your protocol have a corresponding @synthesize for that property, or provide a getter and setter.

Upvotes: 3

Related Questions