在另一个类中访问NSApplications委托?

时间:2011-08-18 20:52:43

标签: objective-c cocoa

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

//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)” 我的错误在哪里?

1 个答案:

答案 0 :(得分:5)

我怀疑您在将任何内容分配给应用程序的del属性之前分配delegate。我建议您完全删除del指针,并在每次需要代理时简单地调用[[NSApplication sharedApplication] delegate]

相关问题