是否可以从另一个类调用@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];
anotherClass.m :
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
//do something here
}
updated :
视图控制器.m:
#import "anotherClass.h"
+(viewcontroller *)myMethod{
// some code...
anotherClass *ac= [[anotherClass alloc]init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
}
anotherClass.h:
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer;
anotherClass.m:
-(void)Viewdidload{
[viewController myMethod];
}
-(void)bannerTapped:(UIGestureRecognizer *)gestureRecognizer {
//do something here
}
是的,像这样
initWithTarget:anotherClassInstance action:@selector(bannerTapped:)];
The Target
是要将事件发送到的类实例。
EDIT
请学会在将来发布您的所有代码,因为您的问题比您提出的问题要复杂得多。长话短说,你不能这样做:
+(viewcontroller *)myMethod{
anotherClass *ac= [[anotherClass alloc]init];
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:ac action:@selector(bannerTapped:)];
}
一旦这个方法完成,ac
将从内存中释放,因为它创建的范围现在已经消失了。使用ARC
这里没有区别。
您需要在这里了解一些不同的事情:
-
+(void)
使其成为一个类方法,这意味着您无法创建实例变量ac
从某种意义上说,这就是您试图做的事情,但您仍然在错误的地方创建它。
- 我怀疑(只是根据代码猜测)你认为
ac
指向当前位于导航堆栈中的viewController。ac
是该类的全新副本。您创建了一个新副本,该副本不会在任何地方显示或在任何地方使用,并在该方法完成后立即消失。
我的第一段代码回答了您提出的问题,即如何从另一个类调用选择器。您现在的问题是您不了解对象流、内存管理、类实例以及类方法与实例方法。
请更多地学习 Objective-C 和面向对象编程,然后再试一次。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)