点击UIBarButtonItem时App崩溃,求技术解决方案
问题根源与解决方案
看起来你遇到的崩溃核心问题是类方法和实例方法的调用不匹配,咱们来一步步理清楚:
问题分析
- 你定义的
AddNewContact是一个类方法(用+符号声明),所以方法内部的self指代的是AddressBookAccess这个类本身,而不是它的实例对象。 - 但你给
UIBarButtonItem绑定的action是@selector(pressButton:),这是一个实例方法(用-符号声明)。类对象无法响应实例方法,所以当你点击按钮时,系统会抛出unrecognized selector sent to class的崩溃。
解决方案
根据你的使用场景,有两种可行的修正方式:
方案1:将类方法改为实例方法(推荐,符合UI控制器的常规使用逻辑)
把AddNewContact改成实例方法,确保target指向当前控制器实例,这样实例方法pressButton:就能被正确调用:
#import <Foundation/Foundation.h> #include<pthread.h> #import <Contacts/Contacts.h> #import <ContactsUI/ContactsUI.h> #import <ContactsUI/CNContactViewController.h> #import <UIKit/UIKit.h> @interface AddressBookAccess : UIViewController // 改为实例方法声明 - (BOOL)addNewContact; @end @implementation AddressBookAccess - (BOOL)addNewContact { // 确保此处已正确初始化newNavigationController和viewController newNavigationController.navigationBar.topItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back to AReach" style:UIBarButtonItemStylePlain target:self action:@selector(pressButton:)]; [self presentViewController:newNavigationController animated:YES completion:nil]; return YES; } - (IBAction)pressButton:(UIBarButtonItem*)btn { NSLog(@"button tapped %@", btn.title); } @end
方案2:保留类方法,但绑定实例作为target
如果你的业务逻辑必须保留类方法,那需要确保UIBarButtonItem的target是AddressBookAccess的一个有效实例,而不是类本身:
#import <Foundation/Foundation.h> #include<pthread.h> #import <Contacts/Contacts.h> #import <ContactsUI/ContactsUI.h> #import <ContactsUI/CNContactViewController.h> #import <UIKit/UIKit.h> @interface AddressBookAccess : UIViewController + (BOOL)addNewContact; @end @implementation AddressBookAccess + (BOOL)addNewContact { // 创建或获取AddressBookAccess的实例 AddressBookAccess *vcInstance = [[AddressBookAccess alloc] init]; // ...此处补充vcInstance的必要初始化逻辑 newNavigationController.navigationBar.topItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back to AReach" style:UIBarButtonItemStylePlain target:vcInstance action:@selector(pressButton:)]; [viewController presentViewController:newNavigationController animated:YES completion:nil]; return YES; } - (IBAction)pressButton:(UIBarButtonItem*)btn { NSLog(@"button tapped %@", btn.title); } @end
额外小建议
Objective-C的命名规范通常采用小驼峰式(比如addNewContact而非AddNewContact),虽然这不是导致崩溃的原因,但遵循规范能让代码更易读哦。
内容的提问来源于stack exchange,提问作者Dan
相关产品推荐
相关产品推荐

