2011-06-07 56 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]; 

问题解决。我浪费了很多时间来解决这个问题 - 一个经典的例子,太多参与代码,而不是看我想做什么。 我忘记了我第一次看到这张贴的地方 - 无论你是谁,谢谢!