[英]How do I set the default value of a protocol property in objective-c?
我有這個協議。
//MyProtocolClass.h
@protocol MyProtocolDelegate <NSObject>
@optional
@property (nonatomic, assign) int anInteger;
@end
@interface MyProtocolClass:NSObject
@end
然后我在這個類上使用這個協議:
//.h
@interface MyClass:NSObject <MyProtocolDelegate>
@end
//.m
@implementation MyClass
@synthesize anInteger;
-(void) aFunction
{
NSLog(@"%d",self.anInteger);
self.anInteger = 200;
NSLog(@"%d",self.anInteger);
}
@end
我想在變量anInteger
上設置默認值100,以便無論用戶是否設置它都保留該值。
NSLogs應該輸出:
100
200
我知道如何使用函數來執行此操作,但是可以使用屬性來執行此操作嗎? 謝謝。
屬性只是一對方法,一個getter和一個setter。 而已。 它沒有說明如何實現getter和setter。 沒有理由假設根本沒有支持的“價值”。
設置屬性值,
-(void)setAnInteger:(int)anInteger
{
self.anInteger = anInteger;
}
像這樣打電話
[self setAnInteger:100];
[self setAnInteger:200];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.