2011-08-01 32 views
3

好吧,我在尋找,但沒有任何方法可以爲我工作。以下代碼基於許多教程和Apple文檔,但我無法使其工作。任何人都可以幫忙嗎?iOS協議和代表示例

代碼崩潰:obj.delegatee = self; (在類B.h中),方法respondsToSelector和performSelector:withObject也不被識別。

我想設置委託對象,當我們點擊特定的圖片時,將會有一個方法被調用。

類A.H:

@interface AViewController : UIViewController <UIScrollViewDelegate>{ 
    id delegatee; 
} 
@property (nonatomic, assign) id <AViewControllerDelegate> delegatee; 
@end 

@protocol AViewControllerDelegate 
@optional 
- (void) tappedImage:(int)tag; 
@end 

類A.M:

@dynamic delegatee; 
- (void)handleSingleTap:(UIGestureRecognizer *)gestureRecognizer { 
UIImageView *imageView = (UIImageView *)[gestureRecognizer view]; 
int a = imageView.tag; 

if ([self.delegatee respondsToSelector:@selector(tappedImage:)]) 
    [self.delegatee performSelector:@selector(tappedImage:) withObject: [NSNumber numberWithInt:a]]; 

}

類B.h:

#import "AViewController.h" 
@interface BViewController : UIViewController <AViewControllerDelegate> {...} 

類B.m:

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
//... some code 

AViewController *obj = [[[AViewController alloc] init] autorelease]; 
obj.delegatee = self; 
} 

- (void) tappedImage:(int)tag{ 
UIImageView *imgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed: [NSString stringWithFormat: @"%d.png",tag]]]; 
CViewController *NView = [[CViewController alloc] initWithPicture: imgView.image]; 
[self presentModalViewController:NView animated:YES]; 
[NView release]; NView = nil; 
} 

非常感謝任何幫助,我希望它能幫助我理解協議如何工作。

+0

你確定你想要@dynamic?我的猜測是你想要@synthesize來代替。 – Colin

回答

4

兩件事。

  1. (你的崩潰)你宣佈你delegatee作爲@dynamic代替@synthesized這意味着你是負責創建-(void)setDelegatee:(id<AViewControllerDelegate>)(和吸氣)方法。修復:只需將其從@dynamic更改爲@synthesize delegatee;

  2. (您的警告)每當您想要調用您未在協議中明確定義的方法時,則您的協議將需要符合另一協議:)。修復:將NSObject協議添加到您的刪除。

@protocol AViewControllerDelegate<NSObject>

+0

是的!這就是這個問題,非常感謝你用這個例子深入解釋!你只是解決了我的頭痛^^ – Vive

+0

但是我的tappedImage方法在B類內部永遠不會被調用..你能看到並告訴爲什麼..? – Vive

+0

確保delegatee不是零,並且使用performSelector更改協議簽名以取NSNumber而不是int:withObject:實際上會將一個意外的*值傳遞給該方法。 *(NSNumber的指針地址) – Joe

0

我的印象是,使用@dynamic delegatee需要您實現-(id)delegatee(void)setDelegatee:(id)delegatee下。