在AppDelegate中调用一个函数?

时间:2011-11-22 20:18:46

标签: objective-c cocos2d-iphone

UITextField Example in Cocos2d的解决方案(实际上得票最高的答案)之后,我设法做到了除了

[[[UIApplication sharedApplication] delegate] specifyStartLevel];

我把它放在我的场景中,我收到了这个警告:

  

找不到实例方法'-specifyStartLevel'(返回类型默认为'id')

为什么?我清楚地在我的AppDelegate的标题和实现中定义了-specifyStartLevel ...


修改:声明 specifyStartLevel

#import <UIKit/UIKit.h>

@class RootViewController;

@interface AppDelegate : NSObject <UIApplicationDelegate,UITextFieldDelegate> {
    UIWindow            *window;
    UITextField *levelEntryTextField;
    RootViewController  *viewController;
}
- (void)specifyStartLevel;
@property (nonatomic, retain) UIWindow *window;

@end

并实施:

- (void)specifyStartLevel
{
    [levelEntryTextField setText:@""];
    [window addSubview:levelEntryTextField];
    [levelEntryTextField becomeFirstResponder];    
}

4 个答案:

答案 0 :(得分:14)

现在,您的班级对您的委托方法一无所知。您需要将您的委托导入您的实现,而不是您的界面(以避免循环导入)。

例如,

#import "AppDelegate.h"

然后,您应该在嵌套方法调用中将返回的委托强制转换为委托类型。例如:

[(AppDelegate *)[[UIApplication sharedApplication] delegate] specifyStartLevel];

答案 1 :(得分:5)

  1. AppDelegate.h文件中添加您的方法,例如:

    - (void)Welcome
    
  2. AppDelegate.m文件中实施方法,例如:

     - (void)Welcome
     {
         NSLog(@"Welcome")
    
     }
    
  3. 在方法中设置UIApplication委托,例如:

    AppDelegate *appDelegate=[UIApplication sharedApplication] delegate];
    
    [appDelegate Welcome];
    

答案 2 :(得分:3)

您需要将AppDelegate导入到使用

的.m文件中
[[[UIApplication sharedApplication] delegate] specifyStartLevel];

我喜欢用标题导入它,这样可以为我提供快捷方式。

GlobalData.h

#import "AppDelegate.h"
#define APPDELEGATE (AppDelegate *)[[UIApplication sharedApplication] delegate]

然后当我在任何课程中使用它时,我只是

#import "GlobalData.h"

// to gain access to the delegate
AppDelegate * appDelegate = APPDELEGATE;

我使用这种方法,因为我可以将更多#define存储到某些全局常量中 (即soundFXVolume - #define SOUND_FX_V 0.6

答案 3 :(得分:3)

-[UIApplication delegate]返回类型为id<UIApplicationDelegate>的对象,因此编译器只知道该类型的对象响应的方法,甚至认为您的自定义委托响应specifyStartLevel。您可以忽略警告,也可以转换-[UIApplication delegate]的返回值:

[(YourCustomAppDelegate *) [[UIApplication sharedApplication] delegate] specifyStartLevel];