Objective-C 觀察者模式--KVO和NSNotificationCenter的使用

來源:互聯網
上載者:User

標籤:load   after   new   修改   通知   model   move   key   修改屬性   

Objective-C中的KVO和NSNotificationCenter的原理是觀察模式的很好實現, 下面用代碼分別示範下用法

 

KVO的用法

 1 - (void)viewDidLoad { 2     [super viewDidLoad]; 3     // Do any additional setup after loading the view, typically from a nib. 4  5     self.model = [Model new]; 6      7     //添加KVO 8     [self.model addObserver:self 9                  forKeyPath:@"name"10                     options:NSKeyValueObservingOptionNew11                     context:nil];12     13     //發送資訊, 通過修改屬性14     self.model.name = @"v1.0";15      16 }17 18 #pragma mark - KVO方法19 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {20     NSLog(@"%@", change);21 }22 23 - (void)dealloc {24 25     //移除KVO26     [self.model removeObserver:self27                     forKeyPath:@"name"];28 }

 

 

NSNotificationCenter的用法

 1 - (void)viewDidLoad { 2     [super viewDidLoad]; 3     // Do any additional setup after loading the view, typically from a nib. 4      5     //添加 6     [[NSNotificationCenter defaultCenter] addObserver:self 7                                              selector:@selector(notificationCenterEvent:) 8                                                  name:@"SCIENCE" 9                                                object:nil];10     11     //發送資訊12     [[NSNotificationCenter defaultCenter] postNotificationName:@"SCIENCE"13                                                         object:@"v1.0"];14     15 }16 17 #pragma mark - 通知中樞方法18 - (void)notificationCenterEvent:(id)sender {19     NSLog(@"%@", sender);20 }21 22 - (void)dealloc {23     //移除通知中樞24     [[NSNotificationCenter defaultCenter] removeObserver:self25                                               forKeyPath:@"SCIENCE"];26 27 }

 

Objective-C 觀察者模式--KVO和NSNotificationCenter的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.