只是發揮各地與您的代碼。它不起作用,但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;
從優秀碼遠的地方,但我試圖改變你的代碼儘可能少。
偉大的我會嘗試這個儘快,但只是需要告訴的東西,直到我試過你的代碼..我已經做了3分的每一個_有空間環繞它,所以隱藏的文本和全文永遠不會是同樣..它是它的3倍..這一切,但我會嘗試你的代碼與我的條件爲它的一個小鑷子,除非你有一個更好的想法,在3螃蟹鴻溝..感謝任何方式爲您的真正有價值的幫助希望它的工作,但我必須睡它真的很晚:D – 2010-11-06 22:16:05
它的工作先生非常感謝你幫助我的一天 – 2010-11-07 11:26:56