Помимо того факта, что, как упоминал Фенелоуски, вы не используете приписанную строку, в вашей логике много проблем.
Ваш текущий внутренний цикл, вероятно, не будет делать то, что вы ожидаете, что делать ... В основном, внутренний цикл только собирается выполнить, когда либо индекс recipeObject
меньше, чем текущий dividesString
индекс или текущий dividesString
индекс меньше, чем общее количество ключевых слов и, вообще говоря, с этой логикой вы в основном создали зависимости, которые не имеют смысла в том, что вы пытаетесь выполнить.
Вместо того, что вы хотите сделать, это увидеть текущие dividesString
соответствует ли ваши любому ключевому слову в настоящее время в текстовом поле, поэтому, если хотел, чтобы кодировать логику вы пытаетесь с помощью двойной петли, вы могли бы перебрать все ключевые слова во время каждой итерации внешнего цикла и делать, если-иначе сравнение после внутреннего цикла завершения выполнения, например:
- (void)drawTheCell:(Recipe *)recipeObject {
self.recipeTitle.text = recipeObject.title;
// Break up the recipe ingredients into components
NSArray *dividesString = [recipeObject.ingredients componentsSeparatedByString:@", "];
// Create a mutable attributed string so you can maintain
// color attributes
NSMutableAttributedString *listIngredients = [[NSMutableAttributedString alloc] init];
// Loop through the ingredient components
for (int i=0; i < dividesString.count; i++) {
// Add a comma if it's not the first ingredient
if (i > 0) {
NSMutableAttributedString *commaString = [[NSMutableAttributedString alloc] initWithString:@", "];
[listIngredients appendAttributedString:commaString];
}
// Create a boolean to indicate whether a keyword match
// has been found
bool matchFound = NO;
// Loop through your "keywords"
for(int j=0; j < recipeObject.keywords.count; j++) {
// If the current ingredient matches the current keyword
// change the matchFound boolean to true
if ([[dividesString objectAtIndex:i] isEqualToString:[recipeObject.keywords objectAtIndex:j]]) {
matchFound = YES;
break;
}
}
NSMutableAttributedString *attString =
[[NSMutableAttributedString alloc] initWithString:[dividesString objectAtIndex:i]];
if (matchFound) {
NSLog(@"Found a match");
// Make the attributed string green
[attString addAttribute:NSForegroundColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(0, attString.length)];
// Append the ingredient to listIngreditents
[listIngredients appendAttributedString:attString];
}
else {
NSLog(@"Match not found");
// Append the ingredient to listIngreditents
// with the default color
[listIngredients appendAttributedString:attString];
}
}
// Set the label, ex. self.recipeIngredients.attributedText = listIngredients;
}
Но есть более простое решение - я рекомендую воздерживаясь внутренний цикл полностью и с помощью containsObject:
чтобы увидеть, содержит ли массив recipeObject.keywords
текущий компонент, например:
- (void)drawTheCell:(Recipe *)recipeObject {
self.recipeTitle.text = recipeObject.title;
// Break up the recipe ingredients into components
NSArray *dividesString = [recipeObject.ingredients componentsSeparatedByString:@", "];
// Create a mutable attributed string so you can maintain
// color attributes
NSMutableAttributedString *listIngredients = [[NSMutableAttributedString alloc] init];
// Loop through the ingredient components
for (int i=0; i < dividesString.count; i++) {
// Add a comma if it's not the first ingredient
if (i > 0) {
NSMutableAttributedString *commaString = [[NSMutableAttributedString alloc] initWithString:@", "];
[listIngredients appendAttributedString:commaString];
}
NSMutableAttributedString *attString =
[[NSMutableAttributedString alloc] initWithAttributedString:[dividesString objectAtIndex:i]];
// If recipeObject.keywords contains the current
// ingredient, add the green attributed string
if([recipeObject.keywords containsObject:[dividesString objectAtIndex:i]]) {
NSLog(@"Found a match");
// Make the attributed string green
[attString addAttribute:NSForegroundColorAttributeName
value:[UIColor greenColor]
range:NSMakeRange(0, attString.length)];
// Append the ingredient to listIngreditents
[listIngredients appendAttributedString:attString];
}
// Else, simply add the string
else {
NSLog(@"Match not found");
// Append the ingredient to listIngreditents
// with the default color
[listIngredients appendAttributedString:attString];
}
}
// Set the label, ex. self.recipeIngredients.attributedText = listIngredients;
}
Добро пожаловать в Переполнение стека! Пожалуйста, добавьте полезный код и описание проблемы здесь. Публикация [Минимальный, завершенный, проверенный пример] (http://stackoverflow.com/help/mcve), который демонстрирует вашу проблему, поможет вам получить более качественные ответы. Благодаря! –
Каков рецепт «ключевые слова», используемый для внутреннего цикла? –
«ключевые слова» являются объектами текстового поля, и я помещаю объекты внутри массива. – iloveios