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

标签 objective-c cocoa

我目前正在尝试编写我的第一个 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/

相关文章:

ios - NSFetchedResultsController 创建了太多的部分

ios - 从 'NSManagedObject Subclass*' 分配给 'NSEntityDescription *' 的不兼容指针类型

cocoa - 已签名 Mac 应用程序的 "Running"但未运行(XCode 4)

objective-c - @synchronized block 是否保证释放它们的锁?

objective-c - 基于 View 的 NSTableView 中的自定义背景

cocoa - 有没有办法强制 AppKit 在窗口菜单中包含我的无边框 NSWindow 子类?

iphone - UIPickerView 的大小设置不正确

ios - 如何使用 objc 访问此数据集中的元素?

Cocoa 绑定(bind)到数组中的单个对象

ios - XCode、LLVM 和代码优化——最快、最小与无