好的,我正在搜索,但没有任何方法对我有效。以下代码基于许多教程和Apple文档,但我无法使其工作。有人可以帮忙吗?
代码崩溃在: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 :(得分:4)
两件事。
(您的崩溃)您将delegatee
声明为@dynamic而不是@synthesized,这意味着您有责任创建-(void)setDelegatee:(id<AViewControllerDelegate>)
(和getter)方法。修复:只需将其从@dynamic
更改为@synthesize delegatee;
(您的警告)每当您想要调用未在协议中明确定义的方法时,您的协议将需要符合另一个协议:)。修复:将NSObject
协议添加到您的文件中。
@protocol AViewControllerDelegate<NSObject>
答案 1 :(得分:0)
我认为使用@dynamic delegatee
要求您实施-(id)delegatee
和(void)setDelegatee:(id)delegatee
。