2011-01-22 61 views
7

我需要一些帮助,试图了解对象的复杂层次结构中的KVO。让我来设置场景。 MyClass对象具有包含MyPerson对象的可变数组属性。我想观察MyClass的myPeople属性的更改。此外,我还想观察MyPerson对象中包含的所有属性。这里是类定义。如何在NSMutableArray中实现对象的关键值观察

@interface MyClass:NSObject 
{ 
    NSMutableArray *myPeople; 
} 

@property(nonatomic, retain)NSMutableArray *myArray; 

@end 

这里是MyPerson对象,

@interface MyPerson:NSObject 
{ 
    NSString *myName; 
    NSString *myLastName; 
} 

@property(nonatomic, retain)NSString *myName; 
@property(nonatomic, retain)NSString *myLastName; 

@end 

它是正确的观察,我很喜欢下面的方式的属性?

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

不,这是不正确的。您必须观察分别添加到阵列中的任何对象的属性。所以无论何时将一个对象添加到数组中或从数组中删除,都必须将添加/删除观察者添加到/添加/删除的对象中。

+0

感谢您的快速回复。如果数组中的对象是字典(NSDictionary)会怎么样?这种方法会起作用吗? – David 2011-01-22 18:58:38