是的,您通常会将每个属性设置为 a@property
并提供一个自定义设置器,该设置器拒绝或纠正无效值:
.h 文件:
@interface Employee : NSObject
@property (assign, nonatomic, readwrite) int personality;
// others omitted
@end
.m 文件:
@implementation Employee
- (void)setPersonality:(int)personality {
if (personality < 1)
personality = 1;
else if (personality > 99)
personality = 99;
// _personality is an auto-generated backing instance variable
_personality = personality;
}
// - (int)personality { ... } will be auto-generated
如果这些属性中的每一个都有一个最小值/最大值,那么创建一个static
函数来限制该值:
static int restrict(int minValue, int maxValue, int value) {
if (value < minValue)
value = minValue;
else if (value > maxValue)
value = maxValue;
return value;
}
...
- (void)setPersonality:(int)personality {
// _personality is an auto-generated backing instance variable
_personality = restrict(1, 99, personality);
}
注意:您不得_personality
直接分配(和朋友);您必须使用self.personality = 34;
或employee.personality = 34;
调用设置器。