iPhone - 无法识别的选择器,“可能不会响应addTarget”
我正在研究一个基本的iPhone应用程序来测试一些事件,并且我遇到了一个我无法理解或找到任何答案的错误。我根本没有使用IB(除了它创建的MainWindow.xib)。iPhone - 无法识别的选择器,“可能不会响应addTarget”
现在,它是尽可能基本的。
mainAppDelegate.h
#import <UIKit/UIKit.h>
#import "mainViewController.h"
@interface mainAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
mainViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) mainViewController *viewController;
@end
mainAppDelegate.m
#import "mainAppDelegate.h"
@implementation mainAppDelegate
@synthesize window;
@synthesize viewController;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.viewController = [[mainViewController alloc] init];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
- (void)dealloc {
[viewController release];
[window release];
[super dealloc];
}
@end
mainViewController.h
#import <UIKit/UIKit.h>
@interface mainViewController : UIViewController {
}
- (void)showMenu;
@end
mainViewController.m
#import "mainViewController.h"
@implementation mainViewController
- (void)loadView {
UIScrollView *mainView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
mainView.scrollEnabled = YES;
self.view = mainView;
self.view.backgroundColor = [UIColor grayColor];
[self.view setUserInteractionEnabled:YES];
[self.view addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchDown];
[mainView release];
}
- (void)showMenu {
NSLog(@"Show Menu");
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
- (void)dealloc {
[super dealloc];
}
@end
现在,我得到一个警告,在这条线:
[self.view addTarget:self action:@selector(showMenu) forControlEvents:UIControlEventTouchDown];
,说-addTarget“的UIView可能不响应 ':动作:forControlEvents:'。这是没有意义的,因为UIView子类当然可以响应addTarget,并且我在self.view上调用它,它必须存在,因为直到loadView结束才释放它。 (甚至那么它应该可以由控制器保留)
寻找以跟踪显示实际的错误是 - [UIScrollView中addTarget:动作:forControlEvents:]:无法识别的选择发送到实例0x5f11490
所以它看起来这是选择器本身的问题,但我看到我的选择器没有错!
我对此很困惑,任何帮助都会很棒。
首先,类总是以大写字母开始....
UIScrollView
是UIView
一个子类,而不是UIControl
。
UIControl
implements addTarget:action:forControlEvents:
。 UIScrollView
没有。因此,运行时错误。
如果您希望响应在滚动视图上采取的操作而发生某些情况,请为滚动视图设置委托。见UIScrollViewDelegate
's documentation。
尝试这种微妙的变化
[self.view addTarget:self action:@selector(showMenu:)
forControlEvents:UIControlEventTouchDown];
这
- (void)showMenu:(id) sender {
NSLog(@"Show Menu");
}
谢谢Aaron,解决了我的问题。我正在关注官方的Facebook SDK文档,冒号失踪。 – andyc 2011-12-30 13:06:57
“UIControl”的+1。作为进一步的见解,'UIControl'就是你所有的'UIControlEvents',例如触摸或修改。如果对象不是'UIControl'的子类,那么你就不能在它上面使用这些事件。一个简单的例子就是打开一个包含视图的XIB。点击视图,进入检查器窗口,你会看到它没有任何控制事件。现在,如果转到inspector窗口的最后一个选项卡并将其设置为“UIControl”子类而不是“UIView”,那么它神奇地包含了所有可以连接的事件。 – iwasrobbed 2010-07-22 16:10:11
谢谢,这正是我需要知道的。我应该知道检查。 当你说'班总是以大写字母开头' - 那是公约还是必要的? – 2010-07-22 16:31:25
Objective-C公约,尽管我们许多人认为有必要避免引起混乱的疯狂。 :) – bbum 2010-07-22 16:42:35