0

グローバル変数と nsrunloop の組み合わせを使用して、アプリケーション全体で同期を強制していることに気づきました。それは機能しますが、私には少し醜いようです。同じ結果を達成する他の方法はありますか?

一般的な例を次に示します。

ParkingSpots *parkingSpots = [[[ParkingSpots alloc] initWithMapViewController:self] autorelease];
        keepRunning = YES;
        NSRunLoop *theRL = [NSRunLoop currentRunLoop];
        while (keepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);

        UpdateLocation *updatedLocation = [[[UpdateLocation alloc] initWithUserid:@"me" andCoordinate:annotation.coordinate withMapViewController:self]
                                           autorelease];
        NSLog(@"Lat = %f, Long = %f",annotation.coordinate.latitude,annotation.coordinate.longitude);
        [updatedLocation sendUpdate];

このコードでは、parkingSpots オブジェクトが完全に初期化されるまで待ってから updateLocation を初期化する必要があります。updatelocation は、parkingSpots が完全に初期化されることを想定しているため、runloop がないと updatelocation は適切に初期化されませんでした。runloop を使用すると、すべてが期待どおりに機能します。

ただし、これは非常に見苦しく見えます (コードのさまざまなポイントでグローバル変数を設定します)。よりエレガントなソリューションはありますか?よろしくお願いします。

4

2 に答える 2

2

クラスでデリゲート パターンを使用し、ParkingSpots初期化が完了したらデリゲートを呼び出すことができます。例えば

ParkingSpots *parkingSpots = [[[ParkingSpots alloc] initWithMapViewController:self] autorelease];
parkingSpots.delegate = self;
parkingSpots.didInitialiseSelector = @selector(parkingSpotsInitialised:);
[parkingSpots startLengthyInitialisation];

- (void) parkingSpotsInitialised:(ParkingSpots*)parkingSpots {
  UpdateLocation *updatedLocation = [[[UpdateLocation alloc] initWithUserid:@"me" andCoordinate:annotation.coordinate withMapViewController:self] autorelease];
}

通知を使用して同じことを達成することもできます。

于 2009-09-30T14:28:02.440 に答える
0

Objective-C の同期機能を確認する必要があると思います。

于 2009-09-30T13:42:22.570 に答える