我正在为OS X开发一个应用程序,我遇到了问题。
I'm developing an app for OS X and I got stuck with a problem.
应用程序的结构是:
-
AppDelegate:主要操作发生在MainMenu.xib。
AppDelegate: where the main actions take place from MainMenu.xib. It's also where the main window is created.
SettingsWindowController:其中设置窗口通过SettingsWindow.xib的接口定义。
SettingsWindowController: where a settings window is defined with interface from SettingsWindow.xib.
我创建了一个协议SettingsWindowProtocol委派这两个类。
I created a protocol SettingsWindowProtocol to delegate those two classes.
我创建了一个类dbHandler,
I created one more class dbHandler which is initialized as an obj dbh in AppDelegate.
在SettingsWindowProtocol中,我创建了一个方法来发送对象,这个方法在SettingsWindowControl对象为null。
In SettingsWindowProtocol I created a method to send the object but after I call this method in SettingsWindowControl the object is null.
问题是我如何在两个不同的类共享同一个对象?
The question is how I share in two different classes the same object ?
与问题相关的几个代码块:
A few blocks of code related to question:
AppDelegate.h:
AppDelegate.h:
#import "dbHandler.h" ... @property (retain) dbHandler *dbh; @interface AppDelegate : NSObject <SettingsWindowControllerProtocol> -(dbHandler*)sendDBobject;AppDelegate.m:
AppDelegate.m:
... - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { dbh = [[dbHandler alloc]init]; ... } - (IBAction)settingsButton:(id)sender { if(!settingsWindowController){ settingsWindowController = [[SettingsWindowController alloc] initWithWindowNibName:@"SettingsWindow"]; } [settingsWindowController showWindow:self]; settingsWindowController.delegate = self; } -(dbHandler*)sendDBobject{ return dbh; }SettingsWindowController.h:
SettingsWindowController.h :
#import "dbHandler.h" @protocol SettingsWindowControllerProtocol<NSObject> -(dbHandler*)sendDBobject; @end @interface SettingsWindowController : NSWindowController @property (assign) id<SettingsWindowControllerProtocol> delegate; @property (retain) dbHandler* dbh; @endSettingsWindowController.m:
SettingsWindowController.m:
- (void)windowDidLoad { dbh = [delegate sendDBobject]; [super windowDidLoad]; NSLog(@"settings string returned: %@",[dbh returnString]); }推荐答案
从您的应用程序的任何地方通过 NSApp委托方法。因此,为了得到 dbh 对象,您只需这样做:
You can access your app delegate from anywhere in your app via the NSApp delegate method. So to get the dbh object, you would just do something like this:
AppDelegate *appDelegate = [NSApp delegate]; dbh = appDelegate.dbh;更多推荐
在两个类之间共享对象
发布评论