I need some help trying to understand KVO on a complex hierarchy of objects. Let me set the scenario. The MyClass object has a mutable array property that contains MyPerson objects. I want to observe changes in the myPeople property of MyClass. Furthermore I would like to observe all the properties contained in the MyPerson object as well. Here are the class definitions.
@interface MyClass:NSObject
{
NSMutableArray *myPeople;
}
@property(nonatomic, retain)NSMutableArray *myArray;
@end
Here is the MyPerson object,
@interface MyPerson:NSObject
{
NSString *myName;
NSString *myLastName;
}
@property(nonatomic, retain)NSString *myName;
@property(nonatomic, retain)NSString *myLastName;
@end
Is it correct to observe the properties that I'm interested in the following manner?
MyClass *myClass = [[MyClass alloc] init]; //myPeople is filled with myPerson objects
MySchool *mySchool = [[MySchool alloc] init];
[myClass addObserver:mySchool
forKeyPath:@"myPeople"
options:NSKeyValueObservingOptionNew
context:NULL];
[myClass addObserver:mySchool
forKeyPath:@"myPeople.myName"
options:NSKeyValueObservingOptionNew
context:NULL]; //I am unsure about this one
[myClass addObserver:mySchool
forKeyPath:@"myPeople.myLastName"
options:NSKeyValueObservingOptionNew
context:NULL]; //I am unsure about this one
No, it's not correct. You would have to observe the properties for any object you add to the array separately. So whenever an object is added to or removed from the array, you would have to add/remove your observer to/from the added/removed object(s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With