Question

How do I check how many instances of an NSWindowController do exist already? I want to open multiple windows of the same window controller showing different contents.

the window is opened this way:

....
hwc = [[HistogrammWindowController alloc] init];
....

I know to check an already existing controller:

if (!hwc)
...

But I need to know the number of multiple opened window controllers. How would that look like?

Thanks

Was it helpful?

Solution

You can keep track of each of the window instances in an NSSet, unless you need access to the order in which they were created, in which case use an NSArray. When a window gets presented, add it to the given collection, when it's been closed, remove it. As an added benefit, you can close every open window when the application quits by iterating through the collection.

Perhaps a little something like this:

- (IBAction)openNewWindow:(id)sender {
    HistogrammWindowController *hwc = [[HistogrammWindowController alloc] init];
    hwc.uniqueIdentifier = self.uniqueIdentifier;

    //To distinguish the instances from each other, keep track of
    //a dictionary of window controllers for UUID keys.  You can also
    //store the UUID generated in an array if you want to close a window 
    //created at a specific order.
    self.windowControllers[hwc.uniqueIdentifier] = hwc;
}

- (NSString*)uniqueIdentifier {
    CFUUIDRef uuidObject = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidObject);
    CFRelease(uuidObject);
    return uuidStr;
}

- (IBAction)removeWindowControllerWithUUID:(NSString*)uuid {
    NSWindowController *ctr = self.windowControllers[uuid];
    [ctr close];
    [self.windowControllers removeObjectForKey:uuid];
}

- (NSUInteger)countOfOpenControllers {
    return [self.windowControllers count];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top