I’m currently trying to write my first CoreData-Application, which needs to access the applications delegate for some stuff. So I was trying to make a little variable inside my delegate which I wanted to read to determine if I got the correct delegate. However, it seems like I’m unable to access my delegate and create a new one instead.
Here is my code:
//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
Strangely enough, this code returns “In delegate: Hello, World”, but “Click: (null)”
Where is my error?
I suspect you’re assigning
delbefore anything has been assigned to thedelegateproperty of the application. I’d recommend you get rid of thedelpointer altogether, and simply call[[NSApplication sharedApplication] delegate]each time you need the delegate.