我刚刚开始使用 X-Code 4.2 构建应用程序。我使用单一 View 应用程序模板创建了该应用程序。
我创建了一个 MainIconViewController,它是一个包含图像、标签和按钮的简单 VC。我将 MainIconViewController View 添加到我的 mainViewController View ,当按下按钮时,我在 Main.m 中遇到崩溃,它说:
-[__NSCFType mainButtonPressed:]: 无法识别的选择器发送到实例 0xb867ba0
Main.m 中发生崩溃的行是:
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
现在 buttonPressed: 完全是空的。
有什么办法解决这个问题吗?
我刚刚尝试制作一个全新的项目来重新测试它。我创建了项目,创建了一个包含单个按钮的 viewController 子类。然后我在主视图 Controller 中创建该 View 的实例并将其添加到 View 中。当我按下按钮时,应用程序像以前一样崩溃。
编辑: 这是所有代码:
//MainIconViewController.h
@protocol MainIconViewControllerDelegate <NSObject>
-(void) openFileNamed:(NSString *)name;
-(void) createNewFile;
@end
#import <UIKit/UIKit.h>
@interface MainIconViewController : UIViewController {
}
@property (assign) id <MainIconViewControllerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
- (void)mainButtonPressed:(id)sender;
@end
//////////////////////////////
//MainIconViewController.m
#import "MainIconViewController.h"
@implementation MainIconViewController
@synthesize titleLabel;
@synthesize imageView;
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (void)viewDidUnload
{
[self setTitleLabel:nil];
[self setImageView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
- (void)mainButtonPressed:(id)sender{
}
@end
最佳答案
首先你的方法必须这样声明:
- (IBAction)mainButtonPressed:(id)sender;
然后你必须像这样调用你的 Controller :
MainIconViewController *icon = [[MainIconViewController alloc]initWithNibName:@"your xib name without extension" bundle:nil];
(更安全,但是如果你的 xib 文件的名字和 Controller 一样,那也没关系)
当然,不要忘记通过操作将您的按钮链接到 IB。
还要检查与 MainIconViewController
对应的 xib 的 File's owner
(进入 IB)是否设置为 MainIconViewController。
请注意,这里存在内存泄漏。您可以将 Controller 保留在您的类(class)中,并在不再需要时释放它。如果释放得太早,它会崩溃,因为你的 View 在需要时没有内存中的 Controller 。如果没有释放(就像你在这里做的那样), Controller 会一直留在内存中并且你有内存泄漏。
请注意,Apple 不推荐您这样做(一个 View 层次结构 = 一个 View Controller )。如果你使用 ARC,那可能是你崩溃的问题。
关于iphone - 按下按钮后 Main.m 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7940545/