问题
Ok, i was searching but there wasn't any method that was working for me. Following code bases on many tutorials and Apple documentation, but i can't get it to work. Can anybody help please?
Code is crashing at: obj.delegatee = self; (in class B.h), also methods respondsToSelector and performSelector:withObject aren't recogized.
I want to set delegate object, on which there will be a method called when we tap on particular picture.
class A.h:
@interface AViewController : UIViewController <UIScrollViewDelegate>{
id delegatee;
}
@property (nonatomic, assign) id <AViewControllerDelegate> delegatee;
@end
@protocol AViewControllerDelegate
@optional
- (void) tappedImage:(int)tag;
@end
class 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]];
}
class B.h:
#import "AViewController.h"
@interface BViewController : UIViewController <AViewControllerDelegate> {...}
class 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;
}
Many thanks for any help, i hope it will help me to understand how protocols work.
回答1:
Two things.
(Your Crash) You declared your
delegatee
as @dynamic instead of @synthesized which means you are responsible for creating the-(void)setDelegatee:(id<AViewControllerDelegate>)
(and the getter) method. Fix: Simply change it from@dynamic
to@synthesize delegatee;
(Your warnings) Whenever you want to call methods that you do not explicitly define in your protocol, then your protocol will need to conform to another protocol :). Fix: Add the
NSObject
protocol to your decleration.
@protocol AViewControllerDelegate<NSObject>
回答2:
I was under the impression that using @dynamic delegatee
requires you to implement -(id)delegatee
and (void)setDelegatee:(id)delegatee
.
来源:https://stackoverflow.com/questions/6903712/ios-protocols-and-delegates-on-the-example