跨类访问 NSMutableDictionary
我在 AppController.h 中声明了一个 NSMutableDictionary 对象,并在相应的 AppController.m 文件中进行了初始化。
AppController.h
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
AppController.m
#import "AppController.h"
@implementation AppController
- (id)init
{
uberDict = [NSMutableDictionary new];
return self;
}
现在我想在另一个视图 flashcardView 中使用 NSMutableDictionary 对象。我使用 AppController 类中的方法添加/删除字典中的项目,并希望在 flashcardView 视图中使用相同的字典(其中当前项目仍然存在)。问题是我不知道如何从 AppController 外部访问字典对象。我该怎么做呢?
来自 flashcardView.m
- (void)setAndCheckString
{
NSArray *keys = [uberDict allKeys];
NSString *i;
for (i in keys) {
string = i;
NSLog(@"%@", string);
}
}
这就是问题所在。我该如何使用 uberDict 来完成这项工作?谢谢!
I have declared an NSMutableDictionary object in AppController.h and initialized in the corresponding AppController.m file.
AppController.h
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject {
NSMutableDictionary *uberDict;
}
AppController.m
#import "AppController.h"
@implementation AppController
- (id)init
{
uberDict = [NSMutableDictionary new];
return self;
}
Now I want to use the NSMutableDictionary object in another view, flashcardView. I add/remove items in the dictionary using methods in the AppController class and want to use the same dictionary (with the current items still present in it) in the flashcardView view. The problem is that I don't know how to access the dictionary object from outside AppController. How would I do that?
from flashcardView.m
- (void)setAndCheckString
{
NSArray *keys = [uberDict allKeys];
NSString *i;
for (i in keys) {
string = i;
NSLog(@"%@", string);
}
}
Here's where the problem lies. What do I do with uberDict to make this work? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
虽然我鼓励您查看替代设计模式,但要做您正在寻找的事情,您只需添加一个方法(或属性)来访问 uberDict 到 AppController。作为一项属性,代码为:
在 AppController.h 文件中,只需添加一行 @synthesize uberDict;在 AppContoller 实现内部(@end 之前)。不用担心(只读)——这意味着获取 uberDict 的对象无法将其设置为新字典,但仍然可以修改字典的内容并从中读取。
While I encourage you to look at alternative design patterns, to do what you're looking for you simply need to add a method (or property) to access uberDict to AppController. As a property, the code would be:
in the AppController.h file, and just add a one line @synthesize uberDict; inside the AppContoller implementation (before the @end). Don't worry about the (readonly) -- this means that the object getting the uberDict cannot set it to a new dictionary, but still can modify the contents of the dict and read from it.