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?
@property
can also appear in the declaration of a protocol or category.
Stated in the official apple documentation . So no problem there.
您可以在协议中拥有属性,前提是每个符合您协议的类都具有该属性的相应@synthesize
,或者提供getter和setter。
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).
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
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.