1. 程式人生 > >object-c中delegate使用簡單方法

object-c中delegate使用簡單方法

最近又剛剛翻過頭來寫iPhone的程式碼

原來使用Xcode2版本,現在都4了

安裝完Xcode4新建工程,我暈了.....(不解釋了)

現在作為菜鳥,從頭記筆記,先看看用處最多的delegate代理

首先是宣告定義部分:

CContentViewController.h檔案

@class CContentViewController;

@protocol CsContentViewDelegate

@required  //必需要實現的方法
- (void)CContentViewControllerDidFinish:(CContentViewController *)controller;


@end


@interface CContentViewController : UIViewController
{

  //成員變數
   
}

@property (assign, nonatomic)  id CContentViewDelegate delegate;

- (IBAction)back:(id)sender;

@end

CContentViewController.m檔案

- (IBAction)back:(id)sender {
    //[self dismissModalViewControllerAnimated:YES];
    [self.delegate ChatsContentViewControllerDidFinish:self];
}


RootViewController.h檔案

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

@interface RootViewController : UIViewController 
<CContentViewDelegate;
{

}

- (IBAction)showCV:(id)sender;

@end

RootViewController.m檔案
#import "RootViewController.h"
#import "AnimationViewController.h"
#import "CContentViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation RootViewController

- (IBAction)showCV:(id)sender {
    CContentViewController *controller = [[CContentViewController alloc]
                                           initWithNibName:@"CContentViewController"
                                           bundle:nil];
    self.title = @"首頁";
    controller.delegate = self;  //設定委託的收聽物件為RootViewController
    //[self presentModalViewController:controller animated:YES];    
    
    [self.navigationController pushViewController:controller animated:YES];
    
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.3];
    [animation setType: kCATransitionMoveIn];
    [animation setSubtype: kCATransitionFromTop];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];    
    
    [self.navigationController.view.layer addAnimation:animation forKey:nil];
    //[controller release];
}

#pragma mark - CContentView View
//實現委託中的方法
//RootViewController會監聽到這個事件並執行。 

- (void)CContentViewControllerDidFinish:(ChatsContentViewController *)controller
{
    //[[self parentViewController] dismissModalViewControllerAnimated:YES];
    [[self navigationController]; popViewControllerAnimated:YES];
}

@end


其中重點的地方是

controller.delegate = self; //設定委託的收聽物件為RootViewController

當CContentViewController發CContentViewControllerDidFinish訊息RootViewController才會監聽到