gpt4 book ai didi

objective-c - 访问另一个类中的 NSApplications 委托(delegate)?

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

我目前正在尝试编写我的第一个 CoreData-Application,它需要访问应用程序委托(delegate)来获取某些内容。因此,我试图在我的委托(delegate)中创建一个小变量,我想读取该变量以确定我是否获得了正确的委托(delegate)。但是,我似乎无法访问我的委托(delegate)并创建一个新的委托(delegate)。这是我的代码:

//delegate.h
#import <Cocoa/Cocoa.h>

@interface delegate_TestAppDelegate : NSObject <NSApplicationDelegate> {
@private
NSWindow *window;
NSString * myString;
}

@property (assign) IBOutlet NSWindow *window;
@property (retain) NSString * myString;

@end

//delegate.m
#import "delegate_TestAppDelegate.h"

@implementation delegate_TestAppDelegate

@synthesize window, myString;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.myString = @"Hello, World";
NSLog(@"In delegate: %@", self.myString);
}

@end

//MyClass.h
#import <Foundation/Foundation.h>
#import "delegate_TestAppDelegate.h"


@interface MyClass : NSObject {
@private
delegate_TestAppDelegate * del;
}
- (IBAction)click:(id)sender;

@end

//MyClass.m
#import "MyClass.h"

@implementation MyClass

- (id)init
{
self = [super init];
if (self) {
del = [[NSApplication sharedApplication] delegate];
}

return self;
}

- (void)dealloc
{
[super dealloc];
}

- (IBAction)click:(id)sender {
NSLog(@"Click: %@", del.myString);
}
@end

奇怪的是,这段代码返回“In delegate: Hello, World”,但是“Click: (null)”我的错误在哪里?

最佳答案

我怀疑您在将任何内容分配给应用程序的 delegate 属性之前就分配了 del 。我建议您完全摆脱 del 指针,只需在每次需要委托(delegate)时调用 [[NSApplication sharedApplication] delegate] 即可。

关于objective-c - 访问另一个类中的 NSApplications 委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7114011/

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