2011-08-18 13 views
1

我目前正在嘗試編寫我的第一個CoreData-Application,它需要訪問某些東西的應用程序委託。所以我試圖在我的委託中創建一個小變量,我想讀取它來確定我是否得到了正確的委託。但是,似乎我無法訪問我的委託並創建一個新委託。 這裏是我的代碼:訪問另一個類中的NSApplications委託?

//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 

奇怪的是,該代碼返回「在委託:你好,世界」,但「點擊:(空)」 哪裏是我的錯誤?

+0

你在哪裏初始化MyClass? – thomashw

+0

作爲Interface Builder中的NSObject –

回答

5

我懷疑在將任何東西分配給應用程序的delegate屬性之前,您正在分配del。我建議你完全擺脫del指針,每次需要委託時只需致電[[NSApplication sharedApplication] delegate]即可。