0

そのため、xml ファイルを要求して解析するアプリを構築しています。次のコードは名前をラベルに入れ、残りのデータはテキスト ビューに入れます。ここで、ループが実行された回数をカウントする if ステートメントに条件を含め、最初の 2 つの要素のみを返します。または、少なくともそれは私がすべきことだと思います。

repCount は、最初は 0 に設定されています。

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURIqualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { WeatherItem *weatherItem = [[WeatherItem alloc] init];

//Is a Location node
if ([elementName isEqualToString:@"Location"])
{

    weatherItem.name = [attributeDict objectForKey:@"name"];

    locationLabel.text = [NSString stringWithFormat:@"%@", weatherItem.name];

    NSLog(@"weatherName---> %@", weatherItem.name);

}

//Is a Rep node
if ([elementName isEqualToString:@"Rep"] && repCount  <= 1)
{

    weatherItem.winddir = [attributeDict objectForKey:@"D"];
    weatherItem.visibility = [attributeDict objectForKey:@"V"];
    weatherItem.windspeed = [attributeDict objectForKey:@"S"];
    weatherItem.temperature = [attributeDict objectForKey:@"T"];
    weatherItem.precipprob = [attributeDict objectForKey:@"Pp"];
    weatherItem.weather = [attributeDict objectForKey:@"W"];


    NSLog(@"weatherItem---> %@", weatherItem.precipprob); //easiest value to keep track of

    resultsTextView.text = [NSString stringWithFormat:
                            @"Wind Dir:%@\nVisibility:%@\nWind Speed:%@mph\nTemperature:%@C\nPrecip Prob.:%@%%\nWeather:%@\n",

                            weatherItem.winddir, weatherItem.visibility, weatherItem.windspeed,
                            weatherItem.temperature, weatherItem.precipprob, weatherItem.weather];

    repCount ++;



}

repCount = 0;}

問題は、XML ファイルの最初の 2 つではなく、最後の要素のみを返すことです。ループを 1 回実行すると仮定し (repCount は 0)、resultsTextView を起動します。それを 2 回実行し (repCount は 1 になりました)、resultsTextView に発生するものに追加します。その後、repCount <= 1 のチェックに合格すると停止します。

私は何を逃したのですか?

前もって感謝します。

4

1 に答える 1

0

repCountその理由は、メソッドの最後にクリアする割り当てがあるためだと思います。

repCount = 0;

ゼロへの設定repCountは、メソッドの外部で行う必要があります (初期化時、またはドキュメント開始イベント ハンドラーで)。現在、repCount各要素の後に がリセットされるため、処理するすべての&& repCount <= 1要素に対して条件の一部が真のままであるため、最後の要素のデータが以前のデータを上書きします。

repCount = 0割り当てをparserDidStartDocument:NSXMLParserDelegate のメソッドに移動すると、問題が解決するはずです。

于 2013-03-09T18:12:52.300 に答える