SaffronState
SaffronState

Reputation: 329

KVO on mutable array of custom objects properties

I understand that it may be a duplicate question, but when i tried i am not getting the changed properties. I followed couple of KVO + Array SO answers. However I still missing some bits as its not working in my case.

User.h:

@interface User : NSObject
...
@property(nonatomic, assign) double latitude;
@property(nonatomic, assign) double longitude;
...
@end

SingletonClass.h:

@interface SingletonClass : NSObject
....
@property(nonatomic, readonly) NSMutableArray *remoteUsers;//Stores user objects
...
@end

SingletonClass.m

@implementation SingletonClass

for (int i = 0; i < _remoteUsers.count; i++) {
            index = [NSIndexSet indexSetWithIndex:i];
            User *rmtUser = _remoteUsers[i];
            if ([rmtUser.roomJid isEqualToString:occupantJID.description]) {
                [self willChange:NSKeyValueChangeReplacement valuesAtIndexes:index forKey:@"remoteUsers"];
                rmtUser.latitude = user.latitude;
                rmtUser.longitude = user.longitude;
                [self didChange:NSKeyValueChangeReplacement valuesAtIndexes:index forKey:@"remoteUsers"];
                isUserInList = YES;
                break;
            }
        }

MainViewClass.h: Here I want to update the user location on map.

MainViewClass.m:

@implementation MainViewClass
....
[SingletonClass addObserver:self forKeyPath:@"remoteUsers" options:NSKeyValueObservingOptionNew context:nil];
....

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"remoteUsers"]) {
        User *remoteUser = ((SingletonClass *)object).remoteUsers[0];
        NSLog(@"THE LATITUDE OBSERVED IS %f", remoteUser.latitude);
        NSLog(@"THE LONGITUDE OBSERVED IS %f", remoteUser.longitude);
    }
}

Here I am getting the complete user object instead the changed/updated properties. Am i doing it wrong anywhere?

Upvotes: 0

Views: 183

Answers (2)

SaffronState
SaffronState

Reputation: 329

As @A-Live mentioned its working as expected. There was a type in the real code which is not here in the post.

Upvotes: 0

Proton
Proton

Reputation: 1365

How about if you change your code become to:

[self willChangeValueForKey:@"remoteUsers"];
rmtUser.latitude = user.latitude;
rmtUser.longitude = user.longitude;
[self didChangeValueForKey:@"remoteUsers"];

Upvotes: 0

Related Questions