iOS 簡單代理(delegate)實現

原文地址:http://www.cnblogs.com/lovekarri/archive/2012/03/04/2379197.html


delegate是ios編程的一種設計模式。我們可以用這個設計模式來讓單繼承的objective-c類表現出它父類之外類的特徵。昨天這個代理實現如下:

 

類GifView是繼承自UIView的,它加載在RootViewController上來通過一個Timer播放動畫。同時,RootViewController需要知道Timer的每次執行。

代碼如下。

首先,定義GifView,在其頭文件中定義代理EveryFrameDelegate,同時聲明方法- (void)DoSomethingEveryFrame;

複製代碼
#import <UIKit/UIKit.h>

@protocol EveryFrameDelegate <NSObject>

- (void)DoSomethingEveryFrame;

@end

@interface GifView : UIView 
{
    NSTimer *timer;
    id <EveryFrameDelegate> delegate;
    NSInteger currentIndex;
}

@property (nonatomic, retain) id <EveryFrameDelegate> delegate;

@end
複製代碼

然後,只要在GifView.m中讓Timer在每次執行的時候調用delegate來執行DoSomethingEveryFrame,代碼如下

複製代碼
- (id)initWithFrame:(CGRect)frame
{
    
    self = [super initWithFrame:frame];
    if (self)
    {
        timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(play) userInfo:nil repeats:YES];
        [timer fire];
    }
    return self;
}

-(void)play
{
        [delegate DoSomethingEveryFrame];
 
}
複製代碼

GifView上的工作就完成了。

下面是RootViewController中的代碼,RootViewController只要在定義GifView的時候指定其代理爲自身,就可以知道Timer的每次執行:

複製代碼
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    CGRect rect = CGRectMake(0, 0, 200, 200);
    GifView *tmp = [[GifView alloc] initWithFrame:rect];
    tmp.delegate = self;
    [self.view addSubview:tmp];
    [tmp release];
}

- (void)DoSomethingEveryFrame
{
    NSLog(@"I'm the delegate! I'm doing printing!");
}
複製代碼

GifView中Timer每次執行都會打印一行

I'm the delegate! I'm doing printing!

故,RootViewController就知道Timer的每次執行了。

 

 

 

====================我是歡樂的分割線====================

 

 


以下內容爲2013.3.12添加

在RootViewController的頭文件中需要引入GifView.h這個頭文件,並表明RootViewController遵循代理EveryFrameDelegate。否則會有警告出現。

代碼如下:

#include <UIKit/UIKit.h>
#import "GifView.h"

@interface RootViewController : UIViewController <EveryFrameDelegate>

@end

 

另外,在定義代理的時候加上關鍵字@optional則表明這個代理可以不用實現所有的代理方法而不被報警告。

代碼如下:

複製代碼
@protocol EveryFrameDelegate <NSObject>
@optional

- (void)ifYouNeedThis;
- (void)DoSomethingEveryFrame;

@end
複製代碼
發佈了8 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章