2010-11-16 51 views
0

我試圖學習目標C的協議。我寫了兩個文件,第一個是FirstViewController.h,其中有一個協議「打印」。我使用委託方法「print」在successViewController中聲明FirstViewController類。 問題是控制檯輸出爲「C」的原因。爲什麼我不能得到「B」輸出?爲什麼協議方法沒有執行?一個Objective-C協議的問題

#import <UIKit/UIKit.h> 
#import "FirstViewController.h" 
@interface successViewController : UIViewController <FirstViewControllerDelegate> { 
} 
@end 

#import "successViewController.h" 
#import "FirstViewController.h" 
@implementation successViewController 
- (void)viewDidLoad { 
FirstViewController *firstViewController= [[FirstViewController alloc] init]; 
firstViewController.delegate=self; 
NSLog(@"C"); 
[super viewDidLoad]; 
} 
-(void) print{ 
NSLog(@"B"); 
} 
@end 

#import <Foundation/Foundation.h> 
@class FirstViewController; 
@protocol FirstViewControllerDelegate <NSObject> 
- (void) print; 
@end 
@interface FirstViewController : NSObject { 
id <FirstViewControllerDelegate> delegate; 

} 
@property (nonatomic, assign) id <FirstViewControllerDelegate> delegate; 
@end 

#import "FirstViewController.h" 
@implementation FirstViewController 
@synthesize delegate; 
@end 

回答

0

你需要給你打電話要使用的方法。

[successViewController print];

1

因爲你永遠不調用print方法。你在哪裏期待它被稱爲?

Objective-C協議允許您指定一個類能夠執行某些操作。在你的例子中,successViewController被宣佈爲FirstViewControllerDelegate,這意味着它能夠處理其代表FirstViewController所要求的職責。它更多是類之間的編程契約,可以由編譯器驗證。作爲一個方面說明,Objective-C中的類應始終以大寫字母開頭,方法應始終以小寫字母開頭。您的FirstViewController遵循此規則,但successViewController不符合。

0

您從不打電話給代表print方法。代表不能閱讀您的想法並自動調用內容。讓我們舉一個小例子,說明代表如何工作。

假設我們有一個名爲Delay的類,它唯一要做的就是等待start被調用的時間,然後告訴它的委託它已經等待。可選地,代理可以告訴Delay等待多久,如果客戶不在意,則假定1秒的延遲。

一些規則:

  1. 的所有委託方法第一個參數應該是發送者本身,從來沒有不帶參數的委託方法。
  2. 委託方法名稱應包含一個關鍵詞:
    1. will - 如果事情無法避免發生之前被調用的方法。示例applicationWillTerminate:
    2. did - 如果方法在發生某事之後被調用。例如scrollViewDidScroll:
    3. should - 如果該方法返回一個BOOL如果發生什麼信號。例如textFieldShouldClear:
  3. 名稱的方法來告訴發生了什麼,你所期望的委託做什麼。
    1. 唯一的例外是,如果客戶需要返回一些東西,那麼應該是某個名稱的一部分。例如:tableView:editingStyleForRowAtIndexPath:

下面是簡單的定義和實施。請注意,我甚至不檢查代理是否已設置,因爲nil上的調用方法無論如何都被忽略。

// Delay.h 
@protocol DelayDelegate; 

@interface Delay : NSObject { 
@private 
    id<DelayDelegate> _delegate; 
} 
@property(nonatomic, assign) id<DelayDelegate> delegate; 
-(void)start; 
@end 

@protocol DelayDelegate <NSObject> 
@required 
-(void)delayDidComplete:(Delay*)delay; 
@optional 
-(NSTimeInterval)timeIntervalForDelay:(Delay*)delay; 
@end 


// Delay.m 
@interface Delay 
@synthesize = delegate = _delegate; 

-(void)start { 
    NSTimeInterval delay = 1.0; 
    if ([self.delegate respondsToSelector:@selector(timeIntervalForDelay:)]) { 
    delay = [self.delegate timeIntervalForDelay:self]; 
    } 
    [self performSelector:@selector(fireDelay) withObject:nil afterDelay:delay]; 
} 

-(void)fireDelay { 
    [self.delegate delayDidComplete:self]; 
} 
@end