Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS- protocols and delegates on the example

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.

like image 880
Nat Avatar asked May 25 '26 08:05

Nat


1 Answers

Two things.

  1. (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;

  2. (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>

like image 120
Joe Avatar answered May 30 '26 05:05

Joe