在两个类之间共享对象 [英] Sharing an object between two classes
问题描述
我正在为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;
@end
SettingsWindowController.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;
这篇关于在两个类之间共享对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!