Search code examples
objective-cobserver-patterndecoupling

register a class in objective c


lets say i have classA which is a class of audio,that sample the audio input many times. each time class A get a new data (can happen many times in second), he needs to inform another class, which is classB.

Now, i could just make an instance of class B in classA and call B when there is a new data arrived, but this is not a modular software.

i want classA to be "blind" to the outside, and just to add him to every project, and to have another classB that will register him some how, so when A has something new, B will know about it,(without A calling B ! )

how its done right in objective c ?

thanks a lot .


Solution

  • You can post a notification in ClassA, and register for that notification in other classes (namely ClassB).

    This is how you can do it:

    (in ClassA):

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"noteName" object:self];
    

    (in ClassB):

    [[NSNotificationCenter defaultCenter] addObserver:self
    selector:@selector(doSomething:)
    name:@"noteName" object:nil];
    

    Whenever an instance of ClassA posts a new notification, other instances that have registered to that notification will be informed (instantaneously). In this case, ClassB will perform doSomething:(NSNotification *)note.


    [Edit]

    You can post that notification your setter method (setVar:(NSString*)newVar).

    If you want to pass something along, use the postNotificationName:object:userInfo: variant. userInfo is a NSDictionary and you can pass anything you want in it. for example:

    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:var, @"variable", nil];
    [[NSNotificationCenter defaultCenter]
    postNotificationName:@"noteName" object:self userInfo:dic];
    

    now, edit your doSomething: method:

    -(void)doSomething:(NSNotification*)note {
        if ([[note name] isEqualToString:@"noteName"]) {
            NSLog(@"%@", [note userInfo]);
        }
    }
    

    More info: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html

    https://developer.apple.com/library/mac/#documentation/General/Conceptual/DevPedia-CocoaCore/Notification.html

    https://developer.apple.com/library/mac/#documentation/Darwin/Conceptual/MacOSXNotifcationOv/Introduction/Introduction.html