Question

what is the best way to replicate the c# code below in objective c.

I am using the setter method to add some additional functionallty.

    void someMethod()
    {
        speed = 10; //_speed is 10
        speed++;//_speed is now 11
        speed += 70;//_speed is now 86
        speed += 12324;//_speed is clamped to 100 in setter
    }

    int _speed;
    public int speed
    {
        get { return _speed; }
        set { _speed = value;
            if (_speed > 100)
            {
                _speed = 100;
            }
        }
    }

I know I can do something like this in obj c

@property (nonatomic,assign) NSInteger speed;

which then makes these methods available

-(void)setSpeed:(NSInteger)speed
{

}

-(void)getSpeed:(<#object-type#> **)buffer range:(NSRange)inRange
{
}

however I am uncertain how I can actually access the property internally in my class. What I would like to be able to do is somewhere else in the class instance (and / or from the instantiating object as well) is set speed by doing something like speed = 50 and know the code in the setter will ensure it never exceeds the max.

I hope this makes sense!

Thanks!

Was it helpful?

Solution

Xcode automatically generates the getters and the setters for you when you define the properties, so you have them already, you can access them like this:

self.speed = 5;
int mySpeed = self.speed;

In case you want to overwrite this setter, you can do it:

-(void)setSpeed:(NSInteger)speed
{
    if (speed > maxSpeed)
        _speed = maxSpeed;
    else
        _speed = speed;
}

Take into account that when you use objects, if you implement the setter, you need to release the previous value and retain the new one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top