iphone可可使用nsrunloop的
-
19-09-2019 - |
题
我发现使用全局变量的组合和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对象完全初始化之前我初始化更新位置。由于更新位置预计parkingSpots被完全初始化,而runloop updatedlocation不正确初始化。与runloop一切正常。
然而,这看起来很丑陋,我(在我的代码设置在不同的点一个全局变量)。有没有更好的解决方案?在此先感谢您的帮助!
解决方案
您可以使用您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];
}
您也可以使用通知来实现同样的事情。
其他提示
我认为你需要看看Objective-C的的同步功能。
不隶属于 StackOverflow