2011-08-11 26 views
1

如何調用另一種方法的參數方法。客觀c調用另一種方法的參數

我在目標c類有問題。 我的代碼是

- (void)locationUpdate:(CLLocation *)location { 

    location.coordinate.longitude];  
    googleUrl=[[NSString alloc]initWithFormat:@"https://maps.googleapis.com/maps/api/place /search/xml?location=%f,%f&radius=500&name=the%20money&sensor=false& key=AIzaSyCcC9pmri9XGOgyhjoHQq37cmcfgsfb6bBZe80",location.coordinate.latitude,location.coordinate.longitude]; 

} 



-(void)ParseXML_of_Google_PlacesAPI { 

    NSURL *googlePlacesURL = [NSURL URLWithString:googleUrl]; 

    NSData *xmlData = [NSData dataWithContentsOfURL:googlePlacesURL]; 
} 

我想把googleUrl值parseXML方法

回答

2

你的問題是有些不清楚。我假設您問的是如何將googleUrl值從locationUpdate方法傳遞給ParseXML_of_Google_PlacesAPI方法。

如果是這樣的話,那麼你需要添加一個NSString參數給後一個方法的簽名。

-(void) ParseXML_of_Google_PlacesAPI:(NSString *) googleUrl { ... } 

然後,您可以通過調用使用從locationUpdate方法的語法如下這種方法:

[self ParseXML_of_Google_PlacesAPI:googleUrl]; 

這是否幫助?

(順便說一句,如果你這樣做,有可能不需要設置googleUrl爲伊娃/屬性,只是聲明爲一個的NSString在locationUpdate方法的範圍。)

3

您可以更改簽名您parseXML_of_Google_PlacesAPI方法如下:

-(void) ParseXML_of_Google_PlacesAPI: (NSString*) googleUrl {...} 

此外,修改方法的實現:

NSURL *googlePlacesURL = [NSURL URLWithString:googleUrl]; 
return [NSData dataWithContentsOfURL:googlePlacesURL]; 

然後,您可以調用的實現方法具d如下:

// your previous code with the location 
NSData* googleData = [self ParseXML_of_Google_PlacesAPI:googleUrl]; 

幾點:
- 方法名稱的約定是,它以小寫字母開頭。
- 在更高級別上,您試圖做的是在某個方法(parseXML)中封裝某些功能。這是一個非常好的做法,因爲它會使您的代碼更具可讀性。要注意的一件事是選擇好的方法名稱;我會選擇getXMLDataOfURL:(NSString *)url作爲方法名稱。這將清楚地確定你在這種方法中試圖達到的目標。
- 關於方法的最佳實踐的健康討論可以發現here.

+3

以'get ...'開頭的方法名通常帶有一個指針參數,用於存儲結果,參見參考資料。 [' - [NSData getBytes:range:]'](http://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html#//apple_ref/doc/UID/20000172-CIACCFDG)。 – gcbrueckmann

+0

謝謝@gcbrueckmann,這是我以前不知道的。將更新我的代碼! – Guven

相關問題