我希望有一种方法暂停执行,直到收到通知,然后再继续。然后在收到通知后继续执行。这样做的最佳方法是什么?
答案 0 :(得分:3)
你可以使用NSRunLoop
- (BOOL)method {
__block BOOL finish = NO;
[[NSNotificationCenter defaultCenter] addObserverForName:@"myNotification" object:nil queue:nil usingBlock:^(NSNotification *note) {
finish = YES;
}];
while(!finish) {
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
return YES;
}
答案 1 :(得分:0)
在Swift 5中等待超时的通知
var accountUpdateNotification: Notification?
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: ACCOUNT_UPDATE_NOTIFICATION),
object: nil, queue: nil) { notification in
accountUpdateNotification = notification
}
// Do action that posts notification
let startTime = Date()
let endTime = startTime.addingTimeInterval(10)
while accountUpdateNotification == nil {
let nextTime = Date().addingTimeInterval(0.1)
RunLoop.current.run(until: nextTime)
if nextTime > endTime {
NSLog("Didn't receive notification in time")
return
}
}