代码之家  ›  专栏  ›  技术社区  ›  ennuikiller

使用nsrunloop的iphone cocoa

  •  0
  • ennuikiller  · 技术社区  · 15 年前

    我发现自己在应用程序中使用全局变量和nsrunlop的组合来强制同步。虽然它有效,但我觉得它有点难看。有没有其他方法可以达到同样的效果?

    下面是一个典型的例子:

    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。由于UpDeTeleCoPress预期PARKEN点被完全初始化,没有RunCURLUPDATE位置没有正确初始化。使用runloop,一切都按预期工作。

    不过,这在我看来很难看(在代码中的不同点设置全局变量)。有更优雅的解决方案吗?提前谢谢你的帮助!

    2 回复  |  直到 15 年前
        1
  •  2
  •   Nathan de Vries    15 年前

    您可以在 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];
    }
    

    您还可以使用通知来实现相同的功能。

        2
  •  0
  •   Eimantas    15 年前

    我想你应该看看 synchronization feature .