Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement key value observing of objects in an NSMutableArray

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
like image 697
David Avatar asked Jan 22 '11 18:01

David


1 Answers

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).

like image 89
Ole Begemann Avatar answered Oct 26 '22 19:10

Ole Begemann