2011-01-22 35 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