iphone使用nsrunlop
我发现自己结合使用全局变量和nsrunlop来强制整个应用程序同步。虽然有效,但我觉得有点难看。有没有其他方法可以达到同样的效果 下面是一个典型的例子:iphone使用nsrunlop,iphone,cocoa-touch,synchronization,nsrunloop,Iphone,Cocoa Touch,Synchronization,Nsrunloop,我发现自己结合使用全局变量和nsrunlop来强制整个应用程序同步。虽然有效,但我觉得有点难看。有没有其他方法可以达到同样的效果 下面是一个典型的例子: ParkingSpots *parkingSpots = [[[ParkingSpots alloc] initWithMapViewController:self] autorelease]; keepRunning = YES; NSRunLoop *theRL = [NSRunLoop currentRun
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];
在这段代码中,在初始化updateLocation之前,我需要等待parkingSpots对象完全初始化。由于updatelocation期望parkingSpots完全初始化,因此在没有runloop的情况下updatedlocation没有正确初始化。使用runloop,一切都按预期进行
然而,这在我看来非常难看(在我的代码中的不同点设置一个全局变量)。有更优雅的解决方案吗?提前感谢您的帮助 我认为您需要查看objective-c。您可以在
ParkingSpots
类上使用委托模式,并在完成初始化时调用委托。e、 g
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];
}
您也可以使用通知来实现同样的功能。这似乎只是为了保护代码的“关键区域”不被多个线程执行。我需要的是等待一段代码完成(parkingSpots初始化),然后再运行另一段代码(updatedlocation初始化),然后您应该使用委托设计模式。@Nathan感谢您的建议。我曾考虑过使用通知,但对如何实现它们有点困惑。你认为可以发布一些伪代码来让它更清晰吗?提前谢谢!谢谢,我和你一起去了,这真是太棒了!!