0

これは私を悩ませています。次のコードがあります。

weatherAddress = [NSString stringWithFormat:@"http://google.com"];
    weatherUrl = [NSURL URLWithString:weatherAddress];
    weatherContents = [NSString stringWithContentsOfURL:weatherUrl encoding:NSASCIIStringEncoding error:nil];

if ([viewer.request.URL.relativeString isEqualToString:weatherContents]) {
   //do stuff
}

しかし、実行すると、時々不正なアクセスがスローされます。私が時々言うとき、私は通常50%の時間を意味します. 私は何を間違っていますか?

4

1 に答える 1

1

これはどうですか、weatherContents がクラスで定義されていると仮定すると、次のようになります。

weatherAddress = [NSString stringWithFormat:@"http://google.com"];
weatherUrl = [NSURL URLWithString:weatherAddress];
weatherContents = [NSString stringWithContentsOfURL:weatherUrl encoding:NSASCIIStringEncoding error:nil];

[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIfWeatherReceived) userInfo:nil repeats:NO];

checkIfWeatherReceived次に、次のように呼び出されるメソッドを作成します。

-(void) checkIfWeatherReceived
{
    if(weatherContents)
    {
        if ([viewer.request.URL.relativeString isEqualToString:weatherContents]) {
            //do stuff
        }
    } else {
        [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIfWeatherReceived) userInfo:nil repeats:NO];
    }
}

接続が切断された場合にインターフェイスをロックするものを使用するのは本当に好きではないので、単に「待機させる」などは控えます。これは、気象データが取得されているかどうかを 0.5 秒ごとにチェックします。より速くチェックしたい場合は、TimeInterval を変更してください。データにあまり遅延が見られない場合は、.01 などのように非常に高速にしたい場合があります。また、接続が失われ、データを取得できない場合に何が起こるかについても考慮する必要があります。私はこれをテストしていませんが、すべてのピースがクラスの一部であり、メソッドに対してローカルではないと仮定すると、うまくいくはずです。checkIfWeatherReceivedまた、実際の作業を実際の領域に配置するだけでなく、別のメソッドに分割することもあるでしょうif(weatherContents)

于 2012-07-12T19:58:40.103 に答える