一步一步熟悉Mac app开发(八)之NSNotification

概要

本文主要介绍如何通过NSNotification来实现两个container view之间的数据的交互。

步骤

1、新建项目,打开storyboard,拖拽两个container view至默认的view controller中。


image.png

2、分别为两个Container View中添加Button和Label,并且设置Auto-Label。(不会的同学请参考第一篇文章)


image.png

3、创建两个NSViewController的子类MagicButtonViewController和BalanceViewController


image.png

4.为Container View中的这两个View Controller添加Custom Class。


image.png
image.png

5.拖拽大法,将button拖拽至MagicButtonViewController.m中,将label拖拽至BalanceViewController.h中。

//MagicButtonViewController.m
- (IBAction)btn_magic:(id)sender {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc postNotificationName:@"click" object:self ];
}
//BalanceViewController.h
#import <Cocoa/Cocoa.h>
@interface BalanceViewController : NSViewController
@property (weak) IBOutlet NSTextField *label_balance;
@end
//BalanceViewController.m
#import "BalanceViewController.h"

@interface BalanceViewController ()
@property NSInteger balance;  //余额
@end

@implementation BalanceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
    _balance = 0;  //初始化为0
    
    //监听、执行getCash方法
    NSNotificationCenter *nf = [NSNotificationCenter defaultCenter];
    [nf addObserver:self selector:@selector(getCash:) name:@"click" object:nil];
    
}
//getCash方法
- (void)getCash:(NSNotification*)notification{
    ++_balance;
    _label_balance.stringValue = [NSString stringWithFormat:@"余额:%ld元",_balance];
    
}
@end

6.完成,效果如下。


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.ios高性能编程 (1).内层 最小的内层平均值和峰值(2).耗电量 高效的算法和数据结构(3).初始化时...
    欧辰_OSR阅读 29,671评论 8 265
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,157评论 1 32
  • 对一个人来说,一辈子注定会不时去寻找一些他们自身周围所不能提供的东西,要么他们以为自身周围无法提供,所以放弃了寻找...
    第四重门阅读 473评论 0 0
  • 万家灯火通明,幸福的味道随着呼吸滑入心底,想到一回家就能品尝到可口的饭菜,我便加快了脚步,朝着那个熟悉的胡同走去。...
    神717阅读 214评论 0 0