register a class in objective c

2019-09-17 21:32发布

问题:

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 .

回答1:

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



回答2:

Sounds like you want to implement the Observer Pattern



回答3:

As ennuikiller suggested, an easy way to implement an observer pattern in obj-c is to use NSNotificationCenter class. For further info see its class reference.

Edit

An other way is using KVO (Key Value Observing). This is more complicated but has better performances respect to the first one. For a simple explanation see Jeff Lamarche blog and KVO Reference.

Hope it helps.