EthanChou EthanChou - 6 months ago 13
Objective-C Question

initWithTarget:self doesn't get my class to call selector

I create a class for dealing with dismissing keyboard

custom class:

tapReconizer.h:

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface tapReconizer : NSObject {
UIView* myView;
}

-(void) tapreg:(UIView*)view;

@end


tapReconizer.m:

#import "tapReconizer.h"

@implementation tapReconizer

-(void) tapreg:(UIView*)view {
myView = view;
UITapGestureRecognizer *tapGestureRecognizer;
tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];

tapGestureRecognizer.numberOfTapsRequired = 1;
[myView addGestureRecognizer:tapGestureRecognizer];
}

- (void)singleTap:(UIGestureRecognizer *)recognizer {
[myView endEditing:true];
}


@end


and in my viewcontorller:

tapReconizer* reg = [[tapReconizer alloc]init];
[reg tapreg:self.view];


but it's seems singleTap: doesn't been called.
Can I do this all just in this custom class?

Thanks in advance.

Answer

Your tapReconizer instance (reg) gets deallocated when it goes out of scope at the end of whatever block it is created in.

You need to keep a strong reference to it. The easiest way is probably to make reg an instance variable.

FYI - you probably meant to name your class TapRecognizer. You misspelled recognizer and it is standard practice to name classes to start with uppercase letters. Method and variable names start with lowercase.