Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: what is the equivalent of an event listener in Objective-C?

In some of my learning I saw someone mention that in your view controller you can have a model and have some sort of listener on the model for changes in it. I don't think I'm using the right names for these, which is probably why my searches haven't turned up anything. Essentially I want to move my server calls from the controllers into my models, but I need some sort of listener on them to know when the call is complete to update my views.

like image 610
Jhorra Avatar asked May 08 '12 03:05

Jhorra


3 Answers

look into delegates delegates tutorial

or blocks a bit more advanced basic blocks tutorial

just start with delegates,

you can also use NSNotification NSNotification tutorial but is not recommended as it broadcast to every class, and you might only need to send messages to a specific class not every one

like image 108
manuelBetancurt Avatar answered Sep 24 '22 14:09

manuelBetancurt


Belong to C# world, i have to go to objective c (for my job). I think the event equivalent in objective c is this implementation :

Create protocol with all your event's methods :

@protocol MyDelegate <NSObject>
    - (void)myEvent;
@end

In your class which should send the event, add :

@interface MyClassWichSendEvent : NSObject

@property (nonatomic, retain) IBOutlet id<MyDelegate> delegate;

@end

Raising the event where you want, for example :

- (IBAction)testEvent:(NSButton*)sender
{
    [self.delegate myEvent];
}

Now in your listener class, you should listen the events like this :

Add the protocol to your class that listening

@interface Document : NSDocument<MyDelegate>

In the implementation, on init or in interface builder, you must link delegate of your object instance to listen with self of your class which listen.

In code

-(void)awakeFromNib
{
    myObjToListen.delegate = self;    
}
  • In Interface Builder -> IBOutlet from delegate to your listen's class.

And finally, implement your method in your listener class :

- (void)myEvent
{
    NSLog(@"i have listen this event !");
}

Sorry for my english, i hope that help people who went from java or C#.

like image 42
csblo Avatar answered Sep 25 '22 14:09

csblo


You're looking for KVO - key/value observing:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

http://nachbaur.com/2011/07/29/back-to-basics-using-kvo/

Delegates + Notifications are good for communicating between objects but they don't automatically send msgs when a value changes (which from your question, that is what you are asking about)

like image 23
spring Avatar answered Sep 24 '22 14:09

spring