iOS- protocols and delegates on the example

做~自己de王妃 提交于 2019-12-13 15:06:16

问题


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.

  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>




回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!