5

次の関数の中で、私はブロックを使用しました。しかし、この関数を呼び出すと、ブロックが実行される前でも返されます。Block inturnはスレッドを使用して個別に実行するため、関数はスレッドが戻るのを待たないことを理解しました。しかし、関数の実行を待機させる他の方法、またはブロック自体を使用せずにこのブロックの機能を実現する他の方法はありますか?

-(int)findCurrentZip
{
        CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:[self findCurrentLatitude]
                                                              longitude:[self findCurrentLongitude]];
         int zipcode;
        self.myGeocoder = [[CLGeocoder alloc] init];
        [self.myGeocoder 
         reverseGeocodeLocation:userLocation
         completionHandler: (id)^(NSArray *placemarks, NSError *error) {
             if (error == nil && [placemarks count] > 0)
             {
                 NSLog(@"Placemarks: %@",placemarks);
                 CLPlacemark *placemark = [placemarks objectAtIndex:0]; 
                 NSLog(@"Country = %@", placemark.country);
                 NSLog(@"Postal Code = %@", placemark.postalCode);
                 zipcode = (int)placemark.postalCode;
                 NSLog(@"Locality = %@", placemark.locality);
                 NSLog(@"Country%@",[placemarks lastObject]);
             }
             else if (error == nil && [placemarks count] == 0)
             {
                 NSLog(@"No results were returned.");
             }
             else if (error != nil)
             {

             }
        }];

        return zipcode;
    }
4

1 に答える 1

8

まず、あなたのデザインを考え直すことをお勧めします。このメソッドからzipCode値を返す代わりに、completionHandlerで他のメソッドを呼び出します(プロトコル/デリゲートなどを作成します)。このreverseGeocodeLocation::メソッドには時間がかかる場合があり、結果を待っているメインスレッドの実行を一時停止したくない場合があります。

ただし、ブロックしたい場合は、を使用する(悪用する?)ことを検討してくださいdispatch_semaphore_t。それを0に初期化し、へdispatch_semaphore_waitの呼び出しの後にreverseGeocodeLocation::。completeHandlerで、を使用してシグナルを送信しdispatch_semaphore_signalます。

詳細:ディスパッチセマフォを使用した有限リソースの使用の規制

編集:そして他の提案のように、__block修飾子を使用してzipCodeを宣言します

于 2012-09-03T08:23:08.780 に答える