1
votes

so i need a NSDocument with a backend instance that all views can access and the objects in the backend can access. At the moment i've got a shared instance, but this limits the document to only one. the code is simply like this:

static id sharedInstance = nil;

+(void)initialize {
    if (self == [ApricumBackend class]) {
        sharedInstance = [[self alloc] init];       
    }
}
+ (id)mainBackend {
    return sharedInstance;
}

But this doesn't work the way i want it to. So how can i achieve that one NSDocument has one variable every view can access and how can i get every object in the backend to be able access the backend? I've made a little graph: an awesome graph

Important is also that the objects in the backend object need to have access to the backend object while they "init"

Thanks

1

1 Answers

1
votes

For the objects, you create a common subclass of NSObject that includes the designated initializer:

+ (id)initWithBackend:(Backend *)backend;

Perhaps call it BackendObject. Then your objects should subclass BackendObject and add initializer methods which are appropriate, for example:

+ (id)initWithSomething:(Something *)something backend:(Backend *)backend;

These initializer methods can then call the superclass initializer, and the backend object (which the graph shows as owning them) needs to pass self when it initializes them.

For the views, you can access the document from within the NSView subclass initializer using:

MyDocument *mydoc = [[[self window] windowController] document];

And provide an accessor to get to the backend, which can be held as an instance variable:

Backend *backend = [mydoc backend];