我想检查两个for循环是否返回匹配,如果它们没有发生任何事情但是如果它们不发生我想要打印出一条消息,说“无法找到匹配”。像这样:
if (loop1 == 0 && loop2 == 0) {
NSLog(@"A match could not be found, please check your spelling");
};
因此,我的问题是,如何描述循环以便我可以检查它们给出的值?
以下是循环:
for (SMADoc *aSearch in docs) {
if ([search isEqualToString:[aSearch leadAuthour]]) {
//Open the file that is represented by UrlToDoc for that specific object
[[NSWorkspace sharedWorkspace] openFile:[aSearch urlToDoc]];
}
}
} else {
//The string starts with a number and should be converted to an int and then the array of the numbers should be searched through
int number = atoi(searchC);
NSNumber *sNumber = [NSNumber numberWithInt:number];
for (SMADoc *nSearch in docs) {
if ([sNumber isEqualToNumber:[nSearch docNumber]]) {
[[NSWorkspace sharedWorkspace] openFile:[nSearch urlToDoc]];
}
}
}
提前致谢!
答案 0 :(得分:1)
由于您的自定义类符合KVC,您可以在没有任何循环的情况下与NSPredicate同时执行检查。
表达式表示:如果docs
包含docNumber
为number
或leadAuthour
为search
的对象,请跳过错误消息
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"docNumber == %i || leadAuthour == %@", number, search];
if [[docs filteredArrayUsingPredicate:predicate] count] == 0 {
NSLog(@"A match could not be found, please check your spelling");
}
答案 1 :(得分:0)
我解决了!我开始声明两个整数,每个循环一个,然后检查是否找不到每次迭代的匹配,即:
![search isEqualToString:[aSearch leadAuthour]]
如果这是真的,则int增加1。然后,在遍历数组后,如果int等于数组中的对象数,我就知道没有任何对象匹配,我可以打印出“找不到匹配,请检查拼写“-信息。这就是代码中的样子:
int i = 0;
int j = 0;
for (SMADoc *aSearch in docs) {
if ([search isEqualToString:[aSearch leadAuthour]]) {
//Open the file that is represented by UrlToDoc for that specific object
[[NSWorkspace sharedWorkspace] openFile:[aSearch urlToDoc]];
}
if(![search isEqualToString:[aSearch leadAuthour]]){
i++;
}
if(i == [docs count]) {
NSLog(@"A match could not be found, please check your spelling");
}
}
} else {
//The string starts with a number and should be converted to an int and then the array of the numbers should be searched through
int number = atoi(searchC);
NSNumber *sNumber = [NSNumber numberWithInt:number];
for (SMADoc *nSearch in docs) {
if ([sNumber isEqualToNumber:[nSearch docNumber]]) {
[[NSWorkspace sharedWorkspace] openFile:[nSearch urlToDoc]];
}
if(![search isEqualToString:[aSearch docNumber]]){
j++;
}
if(j == [docs count]) {
NSLog(@"A match could not be found, please check your spelling");
}
}
我不知道是否允许回答你自己的问题,但我的意图是为可能提出同样问题的人提供答案。