0

I have about four classes let us assume A,B,C and D ,Now my classes B,C,D need to observe the value of class A and get notified when the value changes. I have observed the value in class B and I am not able to get notified in the other two classes say C and D. thanks in advance..

- (void)viewDidLoad

{
   [super viewDidLoad];

    newClassAToBeObserved=[[ClassATobeObserved alloc]init];
    [newClassAToBeObserved addObserver:self forKeyPath:@"StatusToken" options:NSKeyValueObservingOptionNew context:NULL];

    ClassB*classB=[[ClassB alloc]init];
    [classB func];

    ClassC*classc=[[ClassC alloc]init];
    [classc func];

}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    if ([keyPath isEqualToString:@"StatusToken"])
    {
        NSLog(@"changed value is : %@",[object valueForKeyPath:keyPath]);
    }
}


-(IBAction)ClickIt

{

 [newClassAToBeObserved setStatusToken:@"TokenExpired"];

 NSLog(@"Value-->%@",newClassAToBeObserved.StatusToken);

}
Super Xtreem
  • 187
  • 1
  • 10
  • Show the code. What are the differences between what works and what doesn't? – Wain Jul 10 '13 at 12:14
  • just a min i will add the code now – Super Xtreem Jul 10 '13 at 12:19
  • You're only adding `self` as an observer... – Wain Jul 10 '13 at 13:00
  • I am registering observer in the func in classB ( "[classB func];")and class C ( "[classC func];"). – Super Xtreem Jul 10 '13 at 13:19
  • How when you don't pass `newClassAToBeObserved` as a parameter? – Wain Jul 10 '13 at 13:43
  • i have allocated that newClassAToBeObserved in classB and classC respectively here is the sample what i did in class B -(void)func { class1=[[ClassTobeObserved alloc]init]; [class1 addObserver:self forKeyPath:@"StatusToken" options:NSKeyValueObservingOptionNew context:NULL]; } -(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { if ([keyPath isEqualToString:@"StatusToken"]) { NSLog(@"changed value in Thread class 1 : %@",[object valueForKeyPath:keyPath]); } } – Super Xtreem Jul 11 '13 at 04:18

2 Answers2

0

You just add an observer on B,C,D with a given name and post a NSNotification everytime something happens in A.

soryngod
  • 1,827
  • 1
  • 14
  • 13
0

I think you're getting a little confused between instances and classes. Observation is instance based, so, when you create 3 different instances of ClassA and add a different object as an observer of each, they are each individually linked. So, when you update the forest instance of ClassA, only the observers attached to that instance will be updated.

To do what you describe, you should instantiate ClassA only once and pass the instance between the classes which want to observe it. Then they can all attach to the same instance and will all receive the callback when it is updated.

Wain
  • 118,658
  • 15
  • 128
  • 151