开发者

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开发者_如何学C = [[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).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜