2011-06-07 58 views
0

我有一個NSTableView列出使用核心數據存儲的標籤。標籤的默認值是'無標題',我需要每個標籤都是唯一的,所以我有一個驗證例程來捕獲空值和非唯一值,並且工作正常。我不希望用戶能夠存儲「無」值標籤,所以我觀察NSControlTextDidEndEditingNotification,它調用下面的代碼:註釋掉NSTable出現後失去焦點:錯誤

- (void)textEndedEditing:(NSNotification *)note { 
    NSString *enteredName = [[[note userInfo] valueForKey:@"NSFieldEditor"] string]; 
    if ([enteredName isEqualToString:defaultTagName]) { 
    NSString *dString = [NSString stringWithFormat:@"Rejected - Name cannot be default value of '%@'", defaultTagName]; 
    NSString *errDescription = NSLocalizedStringFromTable(dString, @"Tag", @"validation: default name error"); 
    NSString *errRecoverySuggestion = NSLocalizedStringFromTable(@"Make sure you enter a unique value for the new tag.", @"Tag", @"validation: default name error suggestion"); 
    int errCode = TAG_NAME_DEFAULT_VALUE_ERROR_CODE; 

    NSArray *objArray = [NSArray arrayWithObjects:errDescription, errRecoverySuggestion, nil]; 
    NSArray *keyArray = [NSArray arrayWithObjects:NSLocalizedDescriptionKey, NSLocalizedRecoverySuggestionErrorKey, nil]; 
    NSDictionary *eDict = [NSDictionary dictionaryWithObjects:objArray forKeys:keyArray]; 
    NSError *error = [[NSError alloc] initWithDomain:TAG_ERROR_DOMAIN code:errCode userInfo:eDict]; 

    NSBeep(); 
    [preferencesWindowsController presentError:error]; 

    unsigned long index = [self rowWithDefaultTag]; 
    [self selectRowIndexes:[NSIndexSet indexSetWithIndex:index] byExtendingSelection:NO]; 
    // [self editColumn:0 row:index withEvent:nil select:YES]; 
    } 
} 

- (unsigned long)rowWithDefaultTag { 
    __block unsigned long returnInt; 
    [managedTags enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { 
    if ([[obj valueForKey:@"name"] isEqualToString:defaultTagName]) { 
    returnInt = idx; 
    *stop = YES; 
    } 
    }]; 
    return returnInt; 
} 

隨着「editColumn」行,該代碼可以工作,所以如果用戶接受默認標記名稱而不進行編輯,則會生成錯誤並顯示,並通過突出顯示錶中相應的行來完成該過程。

但是,我想更進一步,將用戶置於編輯模式。當我取消註釋'editColumn'這一行時,行爲根本不是我所期望的 - tableView失去了它的藍色焦點框,而代表新標記的行是空白的。如果我點擊tableView,行就會變得可見。我在這方面花了很多時間,並且沒有任何地方,所以對此有所幫助將非常感激。

(注:我嘗試使用textDidEndEditing,這也如我所料不循規蹈矩,但那是另外一個問題)

回答

0

回答我的問題。衛生署!

我已經有我用來放用戶在編輯模式下,當他們點擊按鈕,添加一個新的標籤的方法:

- (void)objectAdded:(NSNotification *)note { 
    if ([[note object] isEqual:self]) {  
    [self editColumn:0 row:[self rowWithDefaultTag] withEvent:nil select:YES]; 
    } 
} 

創建通知來調用這個解決了這個問題,並把用戶在編輯模式下正確。重要的是不要試圖在現有的runloop上做到這一點;所以發送通知如下,推遲交付,直到後來的runloop:

// OBJECTADDED is a previously defined constant. 
NSNotification * note = [NSNotification notificationWithName:OBJECTADDED object:self]; 
[[NSNotificationQueue defaultQueue] enqueueNotification: note postingStyle: NSPostWhenIdle]; 

問題解決。我浪費了很多時間來解決這個問題 - 一個經典的例子,太多參與代碼,而不是看我想做什麼。 我忘記了我第一次看到這張貼的地方 - 無論你是誰,謝謝!