UIBarButtonItem 导致“无法识别的选择器发送到实例”
我将 main.m 中的类的实例调用到 Controls.m 类,但它似乎给了我一个“无法识别的选择器发送到实例”错误。知道我在这里做错了什么吗?每次我点击按钮时它都会崩溃,但是这段代码中的 Controls.m 不是设置为 self 吗?找到测试选择器操作应该不会有问题。
Main.m
- (void)loadView {
Controls *ct = [[Controls alloc] init];
[ct addControls];
[ct release];
}
Controls.m
- (void)addControls {
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, mv.frame.size.height-60, mv.frame.size.width, 40)];
UIBarButtonItem *barBtnDataOverlay = [[UIBarButtonItem alloc] initWithTitle:@"Test Button" style:UIBarButtonSystemItemAction target:self action:@selector(test)];
NSArray *toolbarButtons = [[NSArray alloc] initWithObjects:barBtnDataOverlay, nil];
toolbar.items = toolbarButtons;
[mv addSubview:toolbar];
[barBtnDataOverlay release];
[toolbar release];
}
- (void)test {
NSLog(@"TEST button hit");
}
I call an instance to a class in my main.m to my Controls.m class but it seems to be giving me a "Unrecognized selector sent to instance" error. Any idea what I am doing wrong here? Every time I hit the button it just crashes, but isn't Controls.m set to self
in this code? It shouldn't have trouble finding the test selector action.
Main.m
- (void)loadView {
Controls *ct = [[Controls alloc] init];
[ct addControls];
[ct release];
}
Controls.m
- (void)addControls {
UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, mv.frame.size.height-60, mv.frame.size.width, 40)];
UIBarButtonItem *barBtnDataOverlay = [[UIBarButtonItem alloc] initWithTitle:@"Test Button" style:UIBarButtonSystemItemAction target:self action:@selector(test)];
NSArray *toolbarButtons = [[NSArray alloc] initWithObjects:barBtnDataOverlay, nil];
toolbar.items = toolbarButtons;
[mv addSubview:toolbar];
[barBtnDataOverlay release];
[toolbar release];
}
- (void)test {
NSLog(@"TEST button hit");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于没有保留,
ct
将由[ct release]
释放。尝试向您的类添加一个ct
retin 属性以保留它。在类定义中:
在您的实现中:
...
将您的 loadView 更改为以下内容:
或者甚至更简洁:
您还应该在
viewDidUnload
中的某个地方释放ct
顺便说一句,这是在UIViewController 类?那么
loadView
方法可能应该分配view
实例变量。如果您查看 UIViewController 的文档,您将看到以下内容:ct
will be dealloced by[ct release]
as no retain is left. Try to add act
retin property to your class to keep it around.In class definition:
In your implementation:
...
Change your loadView to something like:
Or even neater:
You should also release
ct
somewhere like inviewDidUnload
BTW, is this in a
UIViewController
class? then theloadView
method should probably assign theview
instance variable. If you look in the documentation forUIViewController
you will see this: