开发者

KVO Multiple Objects

开发者 https://www.devze.com 2023-03-18 01:37 出处:网络
I have three objects, Alien, Balloon, and Joystick all of which have a Location property, which I would like to observe from one controller.

I have three objects, Alien, Balloon, and Joystick all of which have a Location property, which I would like to observe from one controller.

when the controller observes a change in the Location variable of any of the objects, it updates the corresponding views' center properties to the model's location..

My problem is when I utilize the following function:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

The parameter Object, which is of type id, is used to search for the correct index in my MutableArray of object models, and then with the corresponding index in my MutableArray of views, I change the center of the view..

However.. because the parameter is of type id, and not (Ball开发者_如何学Gooon *), (Joystick *), or (Alien *), xcode complains that Location is not a member of object in the following code:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    int index;

    if ([keyPath isEqualToString:@"Location"])
    {
        index = [balloons indexOfObjectIdenticalTo:object];

        [[balloonVs objectAtIndex:index] setCenter:CGPointMake(object.Location.x, object.Location.y)];
    }
}

I understand why it's not working.. but don't know how I could fix it.


Dot notation can only be used with statically typed variables, because it needs to know what setter method to use (since property declarations let you choose a custom setter name). In your case, you can just use a normal message send since you know the setter:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    int index;

    if ([keyPath isEqualToString:@"Location"])
    {
        index = [balloons indexOfObjectIdenticalTo:object];

        [[balloonVs objectAtIndex:index] setCenter:CGPointMake([object Location].x, [object Location].y)];
    }
}


You need to cast it to the right type. For instance, instead of :

object.location

...use:

((Balloon *)object).location
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号