没有已知的select器的实例方法
我正在开发一个iOS 4应用程序,使用最新的SDK, XCode 4.2和ARC 。
我已经添加了一个方法到appDelegate.h
#import <UIKit/UIKit.h> @class ViewController; @class SecondViewController; @interface AppDelegate : UIResponder <UIApplicationDelegate> { UINavigationController* navController; ViewController* viewController; SecondViewController* secondViewController; } @property (strong, nonatomic) UIWindow *window; - (void) showSecondViewController; @end
它在appDelegate.m
实现
#import "AppDelegate.h" #import "ViewController.h" #import "SecondViewController.h" @implementation AppDelegate @synthesize window = _window; - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; viewController.title = @"First"; navController = [[UINavigationController alloc] initWithRootViewController:viewController]; self.window.rootViewController = navController; [self.window makeKeyAndVisible]; return YES; } - (void)applicationWillResignActive:(UIApplication *)application { ... } - (void)applicationDidEnterBackground:(UIApplication *)application { ... } - (void)applicationWillEnterForeground:(UIApplication *)application { ... } - (void)applicationDidBecomeActive:(UIApplication *)application { ... } - (void)applicationWillTerminate:(UIApplication *)application { ... } - (void) showSecondViewController { secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; secondViewController.title = @"Second"; [navController pushViewController:secondViewController animated:YES]; } @end
但是,当我在ViewController.m中向该方法发送消息时
- (IBAction)goSecondClicked:(id)sender { [[[UIApplication sharedApplication] delegate] showSecondViewController]; }
我得到以下编译器错误:
自动引用计数问题没有已知的select器“showSecondViewController”的实例方法
任何线索?
您需要将您获得的委托对象转换为:
AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
然后调用appDelegate
的方法
将您的goSecondClicked
操作方法更改为:
- (IBAction)goSecondClicked:(id)sender { [[[UIApplication sharedApplication] delegate] performSelector:@selector(showSecondViewController)]; }
编辑:虽然这种替代适用于给定的情况,应该指出的是编译器不会帮助你,如果你改变你的委托中的方法名称,忘记改变select器调用名称。 所以这个应该慎重使用。
你也可以在你的AppDelegate.h中定义这个macros
#define APP_DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]
在此之后,您可以调用您的select器:
[APP_DELEGATE showSecondViewController];