2013-03-12 26 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