在两个类之间共享对象

编程入门 行业动态 更新时间:2024-10-20 15:59:09
本文介绍了在两个类之间共享对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为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;

更多推荐

在两个类之间共享对象

本文发布于:2023-06-03 12:18:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/473780.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!