如何防止从NSToken字段中的数组中重复选择。我已经实现了委托完成子字符串。
我能够用这种方法删除任何重复项,诚然,这种方法有点笨拙,但它有效:
// Be sure to set the delegate of your NSTokenfield either in IB or in code.
#pragma mark - NSTokenFieldDelegate
-(NSArray *)tokenField:(NSTokenField *)tokenField shouldAddObjects:(NSArray *)tokens atIndex:(NSUInteger)index{
double delayInSeconds = .1;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSArray *aray = [tokenField objectValue];
NSOrderedSet *set = [NSOrderedSet orderedSetWithArray:aray];
aray = [set array];
[tokenField setObjectValue:aray];
});
return tokens;
}
我想说的最好的方法是实现委托shouldAddObjects
。在委托中编写以下代码。
NSString *newVal = [[tokens objectAtIndex:0] description];
NSArray *aray = [tokenField objectValue];
for (NSString * token in aray) {
@try{
if ([token isEqual:newVal]){
return nil;
}
}
@catch (NSException *exception) {
;
}
}