好吧,我在尋找,但沒有任何方法可以爲我工作。以下代碼基於許多教程和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;
}
非常感謝任何幫助,我希望它能幫助我理解協議如何工作。
你確定你想要@dynamic?我的猜測是你想要@synthesize來代替。 – Colin