2013-03-12 54 views
0

如何检查NSWindowController已确实存在多少个实例? 我想打开显示不同内容的同一窗口控制器的多个窗口。检查现有的多个实例

的窗口打开这样:

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

我知道检查已经存在的控制器:

if (!hwc) 
... 

但我需要知道打开的窗口控制器多的数量。那看起来怎么样?

感谢

回答

1

您可以跟踪每个窗口实例的一个NSSet,除非你需要访问它们被创建的顺序,在这种情况下使用NSArray。当窗口出现时,将其添加到给定的集合中,当它关闭时,将其删除。作为一个额外的好处,当应用程序通过遍历集合而退出时,您可以关闭每个打开的窗口。

也许有点像这样:

- (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]; 
} 
+0

你好CodaFi,听起来作为一个简单的方法。你能告诉我你从同一个控制器区分不同的窗口吗?他们都被打开了相同的'hwc'实例。那么,实际上添加到NSSet的是什么?谢谢 – JFS 2013-03-12 21:49:25

+0

你可以给他们所有的唯一标识符 – CodaFi 2013-03-12 21:51:00

+0

我明白了。我对这项业务相当陌生......你能通过代码给我一个提示吗?我从未使用过标识符。谢谢。 – JFS 2013-03-12 21:52:46