您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 中消息傳遞的 8 種方式全解析

編輯:iOS 相關資訊

一、MVC 簡介

MVC 是組織應用中類的一種策略,也是 iOS 開發最常用的設計模式(當然還有 MVVM、VIPER 等,但不在本文討論範圍)。MVC 代表 Model-View-Controller:

Model:應用是什麼(what the app is);Controller:如何呈現 Model;View:你看到的東西。

需要注意:

1. Controller 可以直接訪問 Model 和 View;

2. Model 和 View 不要直接通信;

3. View 和 Model 不依賴於 Controller,這是最基本的,否則工程在測試和維護時會非常麻煩。

二、消息傳遞的 8 種方式

為更好地理解消息傳遞,作者寫了個簡單的 demo,用三個 ViewController 分別展示不同的傳遞方式。

1. Outlet(Controller 訪問 View)

Outlet 應當是 weak 的,因為強 Outlet 不應該參與引用計數。使用很簡單:在 storyboard 上拖出一個控件,然後 control + drag 拖出一個 outlet 即可。別忘了把 ViewController 設置為自定義的類,否則打開輔助編輯界面會無法拖拽。這樣就能用屬性訪問的方式直接操作 label。

2. target-action(盲通信,View 反饋給 Controller)

Up Button 通過 storyboard 拖拽關聯;Down Button 則用代碼添加。先定義處理方法:

-(void)down:(id)sender{
    NSInteger lastNum = self.label.text.integerValue;
    lastNum--;
    self.label.text = [NSString stringWithFormat:@"%ld",lastNum];
}

然後在 viewDidLoad 中用代碼綁定 target-action:

[self.downButton addTarget:self action:@selector(down:) forControlEvents:UIControlEventTouchUpInside];

第二個 ViewController 很簡單:在 Storyboard 上拖出一個 View,把類設為自定義的 CustomAnimateView。點擊 Animate 按鈕後,紅色原點會移動到指定位置,移動時間由 DataSource 提供,移動開始和結束的事件由 Delegate 提供,結束事件同時也由 Block 提供。

3. Delegate(View 傳遞事件給 Controller,也可用於 Controller 傳遞數據,用途廣泛,能解耦)

4. DataSource(View 的數據源,同樣是一種解耦方式)

5. Block(常用來傳遞事件)

首先定義 Protocol、DataSource 以及響應完成的 Block 類型:

@class CustomAnimationView;
typedef void(^AnimationFinishedBlock)();

@protocol CustomAnimationViewDataSource <NSObject>
-(NSTimeInterval)animationDuration;
-(CGPoint)AnimateToPoint;
@end

@protocol CustomAnimationViewDelegate <NSObject>
@optional
-(void)willStartAnimate:(CustomAnimationView *)view;
-(void)didFinishedAnimate:(CustomAnimationView *)view;
@end

然後在 CustomAnimationView 的接口裡定義屬性:

@interface CustomAnimationView : UIView
@property (weak,nonatomic) id<CustomAnimationViewDataSource> datasource;
@property (weak,nonatomic) id<CustomAnimationViewDelegate> delegate;
@property (copy,nonatomic) AnimationFinishedBlock completeBlock;
@end

最後在 Button 的事件中進行事件傳遞:

-(void)animate:(id)sender{
    if (self.datasource == nil || CGPointEqualToPoint(self.circleView.center, [self.datasource AnimateToPoint])){
        return;
    }
    if ([self.delegate respondsToSelector:@selector(willStartAnimate:)]) {
        [self.delegate willStartAnimate:self];
    }
    [UIView animateWithDuration:[self.datasource animationDuration]
        animations:^{
            self.circleView.center = [self.datasource AnimateToPoint];
        }
        completion:^(BOOL finished) {
            if ([self.delegate respondsToSelector:@selector(didFinishedAnimate:)]) {
                [self.delegate didFinishedAnimate:self];
            }
            if (self.completeBlock) {
                self.completeBlock();
            }
        }];
}

讓 SecondViewController 遵循 Delegate 和 DataSource,提供必要方法:

@interface SecondViewController ()<CustomAnimationViewDataSource,CustomAnimationViewDelegate>
@property (weak, nonatomic) IBOutlet CustomAnimationView *customview;
@end

- (void)viewDidLoad {
    [super viewDidLoad];
    self.customview.delegate = self;
    self.customview.datasource = self;
    self.customview.completeBlock = ^(){
        NSLog(@"Got finished action from block");
    };
}

這樣,點擊時就會按 DataSource 提供的時間和終點運行,並能在 Log 中看到監聽事件成功。

第三個 ViewController 有兩個 View(自定義的 RandomChangeColorView),各添加了點擊手勢,點擊時隨機更改自身 backgroundColor。第一個 View 用 KVO 監聽變化,第二個 View 用 Notification 監聽變化。

6. KVO(Model 反饋給 View)

注冊監聽:

static const int PrivateKVOContext = 0;

[self.firstView addObserver:self forKeyPath:@"backgroundColor"
    options:NSKeyValueObservingOptionNew context:(void *)&PrivateKVOContext];

在如下方法中監聽變化:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
    change:(NSDictionary *)change context:(void *)context{
    if (context == &PrivateKVOContext){
        NSLog(@"first view backgroud color changed from KVO");
        NSLog(@"%@",change.description);
    }
}

7. Notification(盲通信,用途廣泛)

在 RandomChangeColorView 的響應事件中廣播:

[[NSNotificationCenter defaultCenter] postNotificationName:KRANDOMCHANGECOLORVIEWNOTIFICATION object:randomColor];

在 ThridViewController 中監聽廣播:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(colorChange:)
    name:KRANDOMCHANGECOLORVIEWNOTIFICATION object:nil];

-(void)colorChange:(NSNotification *)notificaiton{
    NSLog(@"Color chagne from notification");
    NSLog(@"%@",notificaiton.object);
}

注意:注冊 KVO 和通知都應在合適的位置取消注冊:

-(void)viewWillDisappear:(BOOL)animated{
    [self.firstView removeObserver:self forKeyPath:@"backgroundColor"];
    [[NSNotificationCenter defaultCenter] removeObserver:KRANDOMCHANGECOLORVIEWNOTIFICATION];
}

8. Segue(在 ViewController 切換時常用來傳遞信息)

作者在此前的文章中已詳細介紹過各種類型的 segue(嵌入式 Segue、自定義 Segue、Modal Segue 與 Unwind Segue),並附上 demo。

三、代理與 Notification 的區別

代理就像打電話,只有先接通了才能進行信息交流;而 Notification 就像廣播,你收不收聽、多少人收聽都無所謂,反正它只管播。但要特別注意:你跟廣播站注冊了要收聽,可一旦不聽了卻不提前告知,下次廣播站有通知要發給你、卻找不到你,你就可能要遭殃了(App 有可能崩潰)。

Demo 下載鏈接:https://download.csdn.net/detail/hello_hwc/8408187

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved