2012-06-04 42 views
1

首先,我想爲我在編程方面的知識缺乏而感到抱歉。我正在學習和發現,這個網站對我來說是一個巨大的讚美。只有方法執行的最後一行(Objective-C)

我創建了一個程序有三個的UITextField(thePlace,theVerb,theOutput)和兩個UITextView的其中textviews(theOutput)採取從其他的TextView(theTemplate)文本之一,並替換某些字符串與在輸入的文本文本框。

當我點擊一個按鈕時,它會觸發下面列出的方法createStory。這工作正常,但有一個例外。輸出中的文本僅將字符串「數字」更改爲文本字段中的文本。但是,如果我更改方法中的替換'place','number','verb'的順序,只有動詞被改變,而不是數字。

我確定這是一些簡單的修復,但我找不到它。有些人可以幫我解決問題嗎?

- (IBAction)createStory:(id)sender { 
    theOutput.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<place>" withString:thePlace.text]; 
    theOutput.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<verb>" withString:theVerb.text]; 
    theOutput.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<number>" withString:theNumber.text]; 
} 

非常感謝 //周華健

回答

2

的問題是,你重寫theOutput.text內容的每一行; var1 = var2;將覆蓋var1中的數據並將其替換爲var2的內容。

試試這個:

- (IBAction)createStory:(id)sender 
{ 
    NSString* tempStr = [theTemplate.text stringByReplacingOccurrencesOfString:@"<place>" withString:thePlace.text]; 
    tempStr = [tempStr stringByReplacingOccurrencesOfString:@"<verb>" withString:theVerb.text]; 
    theOutput.text = [tempStr stringByReplacingOccurrencesOfString:@"<number>" withString:theNumber.text]; 
} 

這是否有道理? :)

+0

謝謝,這工作。然而,在睡了一晚之後,我想出了一個更加聰明的寫作方式。我不是每次都改變模板的輸出,而是第一次更改模板的輸出,第二次更改第一個輸出的輸出,第二個輸出更改第二個輸出的第三個輸出。 – Emil

+0

theOutput.text = [theTemplate.text stringByReplacingOccurrencesOfString:@「」withString:thePlace.text]; theOutput.text = [theOutput.text stringByReplacingOccurrencesOfString:@「」withString:theVerb.text]; theOutput.text = [theOutput.text stringByReplacingOccurrencesOfString:@「」withString:theNumber.text]; – Emil

0
- (IBAction)createStory:(id)sender { 
    theOutput.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<place>" withString:thePlace.text]; 
    theTemplate.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<verb>" withString:theVerb.text]; 
    theTemplate.text=[theTemplate.text stringByReplacingOccurrencesOfString:@"<number>" withString:theNumber.text]; 
} 

工作的呢?

+0

這是行不通的。最後兩行改變'theTemplate.text',它不會影響'theOutput.text',這大概是我們想要的。 –

+0

wups。這並不是我的意思:P –

0

首先,確保thePlace.texttheVerb.text不返回空值?但這不是你的問題。

NSLog(@"thePlace: %@",thePlace.text); 
NSLog(@"theVerb: %@",theVerb.text); 

你的代碼應該是:

- (IBAction)createStory:(id)sender { 

    NSString * output = theTemplate.text; 

    output = [output stringByReplacingOccurrencesOfString:@"<place>" withString:thePlace.text]; 
    output = [output stringByReplacingOccurrencesOfString:@"<verb>" withString:theVerb.text]; 
    output = [output stringByReplacingOccurrencesOfString:@"<number>" withString:theNumber.text]; 

    theOutput.text = output; 
} 
+1

您忽略將'output'分配給'theOutput.text'。 –

+0

哎呦,謝謝。 – WrightsCS

+0

這也行得通,但是我發現上述評論中描述的更簡單的解決方案。謝謝你的時間! – Emil