views:

91

answers:

1

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!

A: 

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:

@interface AppController : NSObject {
     NSMutableDictionary *uberDict;
}

@property (readonly) NSMutableArray *uberDict;
@end

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.

Jared P
This still doesn't allow flashcardView to "see" uberDict though, does it? I implemented this and it still returned the same error. From my understanding of properties, they only function within the scope of the class and replace getter and setter methods, correct? From a design perspective, is there a better way to get an NSView object to interact with other objects? I only have about a week's knowledge of Obj-c and as far as I know all NSView's must be declared in their own file, but I'm sure that can't be the only way.
ilovetacos
well of course you need to have some way to get to the AppController from the NSView -- I didn't specify which because there are very many and entirely dependent on your application design, however once you have an AppController in some way, you should be able to [[appController uberdict] allKeys] without problem. Common ways to get an NSView to know about an app controller are to declare an IBOutlet on the view, and connect it to the app controller in IB, or (if the AppController is actually the application delegate) [NSApp delegate].
Jared P