Pregunta

In Objective C you write 20 or so RPG attributes like:

@interface Employee : NSObject
{
    NSString *name;
    NSString *nickname;
    NSString *filename;

    // Attributes
    int personality;
    int behaviour;
    int attitude;
    int workrate;
    int morale;
    int health;
}

I want to make all my RPG attributes listen to rules. ie: Personality can be 1-99, health can be 1-100, morale can be 0-100 and so on.

I'd like to know if I can make a class for Attributes that will automatically test whether the number stored is within rules; this way I can save time having to test it for like 20 different fields.

I guess I could use a dictionary, but even if I do this I'd like to make sure the attributes listen to rules.

Is this kind of thing possible?

¿Fue útil?

Solución

Yeah, you'd generally make each attribute a @property and provide a custom setter which either rejects or corrects invalid values:

.h file:

@interface Employee : NSObject

@property (assign, nonatomic, readwrite) int personality;
// others omitted

@end

.m file:

@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

If every one of those attributes has a min/max value then create an static function to restrict the value:

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);
}

Note: that you must not assign _personality (and friends) directly; you must use self.personality = 34; or employee.personality = 34; to invoke the setter.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top