没有已知的选择器实例方法

时间:2011-12-29 19:07:30

标签: iphone objective-c ios automatic-ref-counting

我正在使用最新的SDK XCode 4.2 ARC 开发iOS 4应用程序。

我已向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];
}

我收到以下编译错误:

自动引用计数问题 没有已知的选择器'showSecondViewController'的实例方法

有任何线索吗?

3 个答案:

答案 0 :(得分:5)

您需要将您获得的委托对象强制转换为:

AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];

然后在appDelegate

上调用该方法

答案 1 :(得分:3)

将您的goSecondClicked操作方法更改为:

- (IBAction)goSecondClicked:(id)sender 
{
    [[[UIApplication sharedApplication] delegate] performSelector:@selector(showSecondViewController)];
}

编辑:虽然这个替代方案适用于给定的情况,但应该注意的是,如果更改代理中的方法名称而忘记更改选择器调用上的名称,编译器将无法帮助您。因此,应谨慎使用。

答案 2 :(得分:1)

您也可以在AppDelegate.h上定义此宏

#define APP_DELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]

在此之后,您可以使用以下命令调用您的选择器:

[APP_DELEGATE showSecondViewController];