How to implement the key value of object observation in NSMutableArray

I need help to understand KVO from a complex hierarchy of objects. Let me set the script. The MyClass object has a mutable array property that contains MyPerson objects. I want to observe changes in the myPeople MyClass property. In addition, I would like to observe all the properties contained in the MyPerson object. 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 right to observe the properties that interest me as follows?

 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 
+7
source share
1 answer

No, that is not right. You will need to observe the properties for any object that you add to the array separately. Therefore, whenever an object is added or removed from the array, you will need to add / remove your observer to / from the added / deleted object (s).

+7
source

All Articles