Delegate & Notification
Delegate & Notification
- Subject: Delegate & Notification
- From: Bing Li <email@hidden>
- Date: Mon, 16 May 2011 06:31:59 +0800
Dear all,
I am learning how to use delegate & notification.
An object, WorkingApp, prints a line and posts a notification as follows.
import "WorkingApp.h"
@implementation WorkingApp
- (void) Print
{
NSLog(@"I am doing a tough job!");
[[NSNotificationCenter defaultCenter] postNotificationName:@"Done"
object:self];
}
@end
Another object, Monitor, registered the notification, "Done".
....
@synthesize delegate;
- (void) IHaveDone: (NSNotification *) notification
{
NSLog(@"OK");
if ([self.delegate respondsToSelector:@selector(IHaveDone:)])
{
[self.delegate IHaveDone:self];
}
}
- (void) setUpNotification: (NSString *) notification withSelector:
(SEL) methodName
{
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:methodName name:notification object:nil];
}
- (void) registerNotifications
{
[self setUpNotification:@"Done" withSelector:@selector(IHaveDone:)];
}
- (id) init
{
if (self = [super init])
{
[self registerNotifications];
}
return self;
}
....
A delegate, MonitorDelegate, is implemented as below.
....
@class Monitor;
@protocol MonitorDelegate
@optional
- (void) IHaveDone: (Monitor *) app;
@end
....
An object called, AppController, implements the delegate.
....
@interface AppController : NSObject <MonitorDelegate>
{
Monitor *monitor;
}
@property (nonatomic, retain) Monitor *monitor;
@implementation AppController
@synthesize monitor;
- (void) IHaveDone:(Monitor *)app
{
NSLog(@"I know you have done!");
}
- (void) sayHi
{
NSLog(@"Hi");
}
- (id) init
{
self.monitor = [[Monitor alloc] init];
self.monitor.delegate = self;
[self.monitor.delegate sayHi];
return self;
}
....
In the main code, the above objects are utilized as follows.
WorkingApp *app = [[WorkingApp alloc] init];
AppController *controller = [[AppController alloc] init];
[app Print];
char s[100];
scanf("%s", s);
[app release];
[controller release];
However, even though the line, "I am doing a tough job!", is displayed, the
line, "I know you have done!", is NOT shown! I cannot figure out what
problems exist. Could you please give me a hand on this?
I appreciate so much for your help!
Best,
Bing
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden