use*_*009 4 objective-c instance-methods uitapgesturerecognizer ios7
是否可以从另一个类调用@selector方法?例如,我创建一个方法"bannerTapped:"并从"myViewController.m"类调用它.
myviewcontroller.m:
anotherClass *ac= [[anotherClass alloc]init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
singleTap.numberOfTapsRequired = 1;
singleTap.numberOfTouchesRequired = 1;
cell.conversationImageView.tag = indexPath.row;
[cell.conversationImageView addGestureRecognizer:singleTap];
[cell.conversationImageView setUserInteractionEnabled:YES];
Run Code Online (Sandbox Code Playgroud)
anotherClass.m:
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
//do something here
}
Run Code Online (Sandbox Code Playgroud)
更新:
viewController.m:
#import "anotherClass.h"
+(viewcontroller *)myMethod{
// some code...
anotherClass *ac= [[anotherClass alloc]init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
}
Run Code Online (Sandbox Code Playgroud)
anotherClass.h:
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer;
Run Code Online (Sandbox Code Playgroud)
anotherClass.m:
-(void)Viewdidload{
[viewController myMethod];
}
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
//do something here
}
Run Code Online (Sandbox Code Playgroud)
是的,就像这样
initWithTarget:anotherClassInstance action:@selector(bannerTapped:)];
Run Code Online (Sandbox Code Playgroud)
这Target是您要将事件发送到的类实例.
编辑
请您学习将来发布所有代码,因为您的问题比您提出的要复杂得多.长话短说你不能这样做:
+(viewcontroller *)myMethod{
anotherClass *ac= [[anotherClass alloc]init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
}
Run Code Online (Sandbox Code Playgroud)
一旦这个方法完成,ac将在内存中释放,因为它创建的范围现在已经消失.使用ARC在这里没有区别.
你需要在这里理解一些不同的东西:
+(void)使这成为一个类方法,这意味着您无法创建一个实例变量,ac它在某种意义上是您尝试做的,但您仍然在错误的位置创建它.ac是指向当前在导航堆栈中的viewController.ac是该类的全新副本.您创建了一个新的副本,该副本不会在任何地方显示或在任何地方使用,并在该方法完成后立即死亡.我的第一段代码回答了你问的问题,就是你如何从另一个类调用选择器.您现在的问题是您不了解对象流,内存管理,类实例和类方法与实例方法.
请更多地研究objective-c和面向对象的编程,然后再试一次.