NSNotificationCenter的简单应用

在AppDelegate中添加UITabBarController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    tabBarController = [[UITabBarController alloc] init];

    ChinaViewController* vc1 = [[ChinaViewController alloc] init];    
    
    HubeiViewController* vc2 = [[HubeiViewController alloc] init];
    
    NSArray* controllers = [NSArray arrayWithObjects:vc1, vc2, nil];
    
    tabBarController.viewControllers = controllers;
    
    [self.window addSubview:tabBarController.view];
    
    [self.window makeKeyAndVisible];
    
    return YES;

}

ChinaViewController类中添加方法

-(id)init {    
    if ([super init] != nil) {  
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"China" image:nil tag:1];  
        self.tabBarItem = item;  
        [item release];  
    }  
    return self;     
}  


- (void)viewDidLoad
{
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:)
                                                 name:@"wangsong" object:nil];    
}

- (void)test:(NSNotification*)notify{
    
    NSString *testString = @"Test Notification!";
    
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification"
                                                        message:testString
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
    [alertView show];
    
    [alertView release];
    
}

在HubeiViewController类中添加方法:

-(id)init {  
    if ([super init] != nil) {  
        UITabBarItem *item = [[UITabBarItem alloc] initWithTitle:@"Hubei" image:nil tag:1];  
        self.tabBarItem = item;  
        [item release];  
    }  
    return self;  

添加一个button的响应方法:

- (IBAction)btPressed{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"wangsong" object:nil];
    
}

点击这个button的时候,将会调用ChinaViewController中的(void)test:(NSNotification*)notify方法,弹出alertShow。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值