2011-04-07 68 views
4

我需要用以下URL中的值替換「CurrentLocation」。 「CurrentLocation」是一個預定義的字符串,它給出了一個動態值(我的意思是每次不同的位置/城市名稱)。我需要幫助,如何在Objective-C中做到這一點?如何在Xcode中連接URL中的字符串(Objective-c)?

NSURL *MainURL = [NSURL URLWithString:@"http://news.google.com/news?q=location:CurrentLocation&output=rss"]; 

在JavaScript中,我會做這樣的事情;

var a="Google"; var b=".com"; var c=".np"; var d=a+b+c; document.write(d); 

請有人幫我這個。謝謝!!

回答

12

您可以在NSString類上使用stringWithFormat靜態消息。這將創建一個自動發佈的使用您指定的格式(使用printf樣式格式字符串)的NSString對象。因此,對於您的情況:

// get the current location from somewhere 
NSString * yourCurrentLocation = @"Sydney"; 

// create your urlString %@ is replaced with the yourCurrentLocation argument 
NSString * urlString = [NSString stringWithFormat:@"http://news.google.com/news?q=location:%@&output=rss", yourCurrentLocation]; 
+0

感謝您的快速響應。我按你所描述的方式嘗試,但可悲的是它說「方法調用的爭論太多,預期1,有2。」 :( – Himalay 2011-04-07 01:21:21

+0

@Himalay你一定是犯了一個錯誤,把它複製到你的代碼中,我做了一個verbatum複製並粘貼到我的項目中,並且這些行都被編譯了,試試明確設置yourCurrentLocation(編輯答案) – RedBlueThing 2011-04-07 01:32:52

+0

是的,它現在正在工作..對不起,我誤解了。 – Himalay 2011-04-07 01:41:05

1

也,一個好的方法是stringByAppendingString,這裏是在蘋果網站的更多信息。

NSString *errorTag = @"Error: "; 
NSString *errorString = @"premature end of file."; 
NSString *errorMessage = [errorTag stringByAppendingString:errorString];