Просто поигрался с вашим кодом.Это не работает, но stringByReplacingCharactersInRange не является вашей проблемой.
Ваша игровая логика работает не так, как должна.Возьмите ручку и лист бумаги и «вручную» переберите ваш цикл for, чтобы увидеть, что это должно быть не так.
В следующий раз, если вы смотрели код в течение получаса, возьмите ручку.Это сэкономит вам минимум 4 часа: -)
Есть некоторые проблемы с вашим кодом.Предположим, Kartoffelkäfer
- это слово, которое вы ищете, и пользователь вводит букву f
.
for (int i = textCount-1 ; i>=0; i--) {
NSString *hiddenTextField = [[NSMutableString alloc] initWithString:hiddenText.text];
// you are creating this string in every loop from the text of a (I guess) UITextField.
// I don't know what the content of this text is but I guess it is suppossed to be `______________`
// in every loop you replace the word where you replaced the _ with the correct letter with the string from the textfield.
// Btw, you are leaking this string.
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i/3,1)];
// Kartoffelkäfer has 14 chars so i is 13. And 13/3 is 4. And the character at index 4 is o
// In the next loop i is 12. And 12/3 is 4, too.
// next three loops will give you index 3. Then you get three times index 2, and so one.
// you never reach the letter f, anyway.
if ([aChar isEqualToString:@" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}else{
theRiddle = [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@"_"];
// You should not replace a unmatched character with a _ . Because already matched letters would be overwritten.
}
hiddenTextField = theRiddle;
}
Я предположил, что содержимое hiddenText.text равно @ " _ __ _ __", а содержимое fullText.text - @" Kartoffelkäfer ".Таким образом, hiddentext - это точная длина как fullText.
Что мне пришлось изменить, чтобы заставить это работать:
NSString *theRiddle;
NSString *hiddenTextField = [[[NSMutableString alloc] initWithString:hiddenText.text] autorelease];
for (int i = textCount-1 ; i>=0; i--) {
NSString *aChar=[fullTextField substringWithRange:NSMakeRange(i,1)];
if ([aChar isEqualToString:@" "]) {
theRiddle= [hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:@" "];
}else if ([aChar isEqualToString:character]) {
theRiddle =[hiddenTextField stringByReplacingCharactersInRange:NSMakeRange(i, 1) withString:aChar];
}
else {
theRiddle = hiddenTextField;
}
hiddenTextField = theRiddle;
}
hiddenText.text=theRiddle;
Вдали от хорошего кода, но я пытался изменить ваш код как можно меньше.,