通知监听作业题目以及答案2
建King、Worker、Farmer类,由King发送一个自定义通知Worker和Farmer类监听通知,通知内容为打印“国王万岁”。
答案
创建 king
king.h文档中输入
#import <Foundation/Foundation.h>
@interface King : NSObject
-(void)sendMessage;
@end
king.m文档中输入
#import "King.h"
@implementation King
-(void)sendMessage
{
[[NSNotificationCenterdefaultCenter] postNotificationName:@"MESSAGE"object:nil];
}
@end
创建Worker
Worker.m文档中输入
#import "Worker.h"
@implementation Worker
-(void)dealloc
{
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];
[super dealloc];
}
-(id)init
{
if ([super init])
{
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say) name:@"MESSAGE"object:nil];
}
returnself;
}
-(void)say
{
NSLog(@"国王万岁");
}
@end
创建Farmer
Farmer.m文档中输入
#import "Former.h"
@implementation Former
-(void)dealloc
{
[[NSNotificationCenterdefaultCenter] removeObserver:selfname:@"MESSAGE"object:nil];
[super dealloc];
}
-(id)init
{
if ([super init])
{
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(say) name:@"MESSAGE"object:nil];
}
returnself;
}
-(void)say
{
NSLog(@"国王万岁");
}
@end
KAppDelegate.h文档中输入
#import <UIKit/UIKit.h>
@interface KAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
KAppDelegate.m 文档中输入
#import "KAppDelegate.h"
#import "King.h"
#import "Former.h"
#import "Worker.h"
@implementation KAppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]] autorelease];
//NSNotificationCenter
Worker *w = [Worker new];
Former *f = [Former new];
King *k = [King new];
[k sendMessage];
[k release];
[w release];
[f release];
self.window.backgroundColor = [UIColorwhiteColor];
[self.windowmakeKeyAndVisible];
returnYES;
}
浙公网安备 33010602011771号