gpt4 book ai didi

objective-c - Cocoa:从 AppDelegate.m 调用方法

转载 作者:行者123 更新时间:2023-12-03 16:34:21 26 4
gpt4 key购买 nike

为了更好地理解应用程序中的启动、事件队列和方法,我正在尝试编写一个执行两件事的程序:在启动时和每次用户点击按钮时播放蜂鸣声。到目前为止,它仅在用户点击按钮时播放。我知道可能有多种方法可以播放启动蜂鸣声,但为了使用初始化代码,我想通过从 AppDelegate.m 文件的 applicationDidFinishLaunching 方法中调用我的 beep 方法来实现。

这是我的代码:

日志.h

#import <Cocoa/Cocoa.h>


@interface Log : NSObject {

IBOutlet id button;

}
-(void)beepAndLog;
-(IBAction)buttonPressed:(id)sender;

@end

日志.m

#import "Log.h"


@implementation Log

-(void)beepAndLog {

NSLog(@"The Method Was Called!");
NSBeep();

}

-(IBAction)buttonPressed:(id)sender {

[self beepAndLog];
}
@end

applicationDidFinishLaunching 方法如下所示:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[Log beepAndLog];

}

但是,在 applicationDidFinishLaunching 方法中,XCode 警告我

'Log' may not respond to '+beepAndLog'

事实上,没有发出蜂鸣声,日志内容如下:

MethodResponse[11401:a0f] +[Log beepAndLog]: unrecognized selector sent to class 0x100002100

(“MethodResponse”是我的项目的名称,顺便说一句)

我不确定为什么 Log 不会响应 beepAndLog,因为这是它的方法之一。我调用它不正确吗?我有一种感觉,对于那些更有经验的人来说,这将是痛苦的明显。我是新手。任何帮助,将不胜感激!谢谢!

最佳答案

有两种可能性。当您需要类方法时,您可以将 beepAndLog 定义为实例方法,或者当您在类上调用它时,您想在实例上调用它。

要将其更改为类方法,请将 header 更改为:

+(void)beepAndLog;

以及实现:

+(void)beepAndLog {
NSLog(@"The Method Was Called!");
NSBeep();
}

对于其他解决方案,请确保您有一个 Log 类的实例(可能是单例),然后执行以下操作:

[[Log logInstance] beepAndLog];

来自您的通知方法。 Log 类需要如下所示:

日志.h:

#import <Cocoa/Cocoa.h>

@interface Log : NSObject {
IBOutlet id button;
}

+(Log *)logInstance;

-(void)beepAndLog;
-(IBAction)buttonPressed:(id)sender;

@end

日志.m:

#import "Log.h"

Log *theLog = nil;

@implementation Log

+(Log *)logInstance
{
if (!theLog) {
theLog = [[Log alloc] init];
// other setup (like hooking up that IBAction)
}
return theLog;
}

-(void)beepAndLog {
NSLog(@"The Method Was Called!");
NSBeep();
}

-(IBAction)buttonPressed:(id)sender {
[[Log logInstance] beepAndLog];
}

关于objective-c - Cocoa:从 AppDelegate.m 调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2114059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com