我的应用程序中有一个设置面板。每当用户按下按钮时,对象都会随着 UI 的更新而在另一个线程上更新。我在主视图上有一个单独的标签,它应该在对象完成更新时更新对象计数(无论设置面板是向上还是向下,我都希望发生这种情况)。我已经尝试关注关于这个主题的苹果文档,但它似乎对我来说并不奏效——也就是说,主视图控制器似乎由于某种原因从未收到通知。有人对如何提醒主视图控制器传递给另一个线程的对象已完成更新有任何建议吗?这是我正在使用的代码(其中大部分是从该文档中复制的):
对象等级:
[[NSNotificationCenter defaultCenter] postNotificationName: @"ScaleCountUpdated" object: self];
主视图控制器
- (void)setUpThreadingSupport
{
if (self.notifications) {
return;
}
self.notifications = [[NSMutableArray alloc] init];
self.notificationLock = [[NSLock alloc] init];
self.notificationThread = [NSThread currentThread];
self.notificationPort = [[NSMachPort alloc] init];
[self.notificationPort setDelegate: self];
[[NSRunLoop currentRunLoop] addPort: self.notificationPort
forMode: (NSString *)kCFRunLoopCommonModes];
}
- (void)handleMachMessage:(void *)msg
{
[self.notificationLock lock];
while ([self.notifications count]) {
NSNotification *notification = [self.notifications objectAtIndex: 0];
[self.notifications removeObjectAtIndex: 0];
[self.notificationLock unlock];
[self processNotification: notification];
[self.notificationLock lock];
};
[self.notificationLock unlock];
}
- (void)processNotification:(NSNotification *)notification{
if ([NSThread currentThread] != self.notificationThread) {
// Forward the notification to the correct thread.
[self.notificationLock lock];
[self.notifications addObject: notification];
[self.notificationLock unlock];
[self.notificationPort sendBeforeDate: [NSDate date]
components: nil
from: nil
reserved: 0];
} else {
[self updateScaleCount];
}
}
- (void)updateScaleCount
{
NSLog(@"[ScalesViewController - updateScaleCount]: Scales updated from notification center.");
if([UserDefinedScales areScalesGrouped] == YES){
self.groupCountLabel.text = [NSString stringWithFormat: @"Group Count: %i", [[UserDefinedScales sortedKeys] count]];
} else {
self.groupCountLabel.text = @"Group Count: 1";
}
self.scaleCountLabel.text = [NSString stringWithFormat: @"Scale Count: %i", [UserDefinedScales scaleCount]];
}
主视图控制器 - 视图已加载:
[self setUpThreadingSupport];
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(processNotification:)
name: @"ScaleCountUpdated"
object: nil];
如果您对如何更改此代码以使其正常运行有任何建议,或者有其他解决方案可以实现这一点,我们将不胜感激!谢谢你。