【问题标题】:Notification on background thread updates NSView后台线程更新通知 NSView
【发布时间】:2011-12-25 19:23:48
【问题描述】:

有一个任务需要在一个 NSView 上绘制 N 个图像。 但是一开始我不知道图片的数量,所以我设置它在后台线程中工作。

 [NSThread detachNewThreadSelector:@selector(workInBackgroundThread:) toTarget:self withObject:nil];

当它获得图片数量时,它会发送通知

- (void)workInBackgroundThread:(id)unusedObject {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

//get image amount....

[[NSNotificationCenter defaultCenter] postNotificationName:@"gotImageAmount" object:nil];

//...
//continue to load images

}

我尝试调整 NSView 的大小取决于通知功能中的图像数量

-(void)processGotImagesAmount:(NSNotification*)notification  
{

    //others codes

    [myNSView setFrame:CGRectMake(0,   0, calculateNewWidth, caculatedNewHeight)];//line A

    //others codes

}

但当应用程序执行 A 行时,它会冻结,

[myNSView setFrame:CGRectMake(0,   0, calculateNewWidth, caculatedNewHeight)];

本身没有问题,如果我点击一个bottun调用它,它就可以了!

但它似乎在通知功能中不起作用

欢迎评论

【问题讨论】:

    标签: multithreading cocoa nsnotificationcenter


    【解决方案1】:

    您正在从后台线程发布通知。

    来自 NSNotificationCenter 文档:

    http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html

    在多线程应用程序中,通知总是以 发布通知的线程

    在您的通知处理代码中,您正在更新您必须从主线程执行的 ui。尝试将该代码移至另一个方法,然后在通知处理代码中,使用 performSelectorOnMainThread 调用它。

    另一个选项是没有通知的 GCD。我在这个 S.O. 中发布了一个示例。答案:

    GCD, Threads, Program Flow and UI Updating

    【讨论】:

      猜你喜欢
      • 2023-04-05
      • 2015-10-04
      • 2012-04-24
      • 2013-11-23
      • 2020-01-24
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多