你好,歡迎來到IOS教程網

 Ios教程網 >> IOS基礎知識 >> IOS入門簡介 >> iOS – 委托(Delegates)

iOS – 委托(Delegates)

編輯:IOS入門簡介

委托(Delegates)示例

假設對象A調用B來執行一項操作,操作一旦完成,對象A就必須知道對象B已完成任務且對象A將執行其他必要操作。

在上面的示例中的關鍵概念有

  • A是B的委托對象
  • B引用一個A
  • A將實現B的委托方法
  • B通過委托方法通知

創建一個委托(Delegates)對象

1. 創建一個單一視圖的應用程序

2. 然後選擇文件 File -> New -> File...

addNewFile

3. 然後選擇Objective C單擊下一步

4. 將SampleProtocol的子類命名為NSObject,如下所示

setProtocolName

5. 然後選擇創建

6.向SampleProtocol.h文件夾中添加一種協議,然後更新代碼,如下所示:

#import <Foundation/Foundation.h>
// 協議定義
@protocol SampleProtocolDelegate <NSObject>
@required
- (void) processCompleted;
@end
// 協議定義結束
@interface SampleProtocol : NSObject

{
   // Delegate to respond back
   id <SampleProtocolDelegate> _delegate; 

}
@property (nonatomic,strong) id delegate;

-(void)startSampleProcess; // Instance method

@end

7.修改 SampleProtocol.m 文件代碼,實現實例方法:

#import "SampleProtocol.h"

@implementation SampleProtocol

-(void)startSampleProcess{
    
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate 
	selector:@selector(processCompleted) userInfo:nil repeats:NO];
}
@end

8. 將標簽從對象庫拖到UIView,從而在ViewController.xib中添加UILabel,如下所示:

delegateLabel

9. 創建一個IBOutlet標簽並命名為myLabel,然後按如下所示更新代碼並在ViewController.h裡顯示SampleProtocolDelegate

#import <UIKit/UIKit.h>
#import "SampleProtocol.h"

@interface ViewController : UIViewController<SampleProtocolDelegate>
{
    IBOutlet UILabel *myLabel;
}
@end

10. 完成授權方法,為SampleProtocol創建對象和調用startSampleProcess方法。如下所示,更新ViewController.m文件

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init];
    sampleProtocol.delegate = self;
    [myLabel setText:@"Processing..."];
    [sampleProtocol startSampleProcess];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Sample protocol delegate
-(void)processCompleted{    
    [myLabel setText:@"Process Completed"];
}


@end

11. 將看到如下所示的輸出結果,最初的標簽也會繼續運行,一旦授權方法被SampleProtocol對象所調用,標簽運行程序的代碼也會更新。

delegateResult

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