关于后台线程更新 NSView 的通知
有一个任务需要在 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 称之为它,它有效!
但看起来它在通知功能中不起作用
欢迎任何评论
There is a task needs to draw N images on a NSView.
But at the beginning I do not know the amount of images, so I set it works in a thread of background.
[NSThread detachNewThreadSelector:@selector(workInBackgroundThread:) toTarget:self withObject:nil];
when it get the amount of images, it will send a notification
- (void)workInBackgroundThread:(id)unusedObject {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//get image amount....
[[NSNotificationCenter defaultCenter] postNotificationName:@"gotImageAmount" object:nil];
//...
//continue to load images
}
I try to resize the NSView depends on the amount of images in the notification function
-(void)processGotImagesAmount:(NSNotification*)notification
{
//others codes
[myNSView setFrame:CGRectMake(0, 0, calculateNewWidth, caculatedNewHeight)];//line A
//others codes
}
but when the app executes the line A, it freezes,
[myNSView setFrame:CGRectMake(0, 0, calculateNewWidth, caculatedNewHeight)];
itself has no problem, if I click a bottun to call it, it works!
but it looks like it does not work in a notification function
Welcome any comment
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在从后台线程发布通知。
来自 NSNotificationCenter 文档:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html
在您的通知处理代码中,您正在更新 ui,您必须从主线程执行此操作。尝试将该代码移动到另一个方法,然后在通知处理代码中使用performSelectorOnMainThread 调用它。
另一种选择是没有通知的 GCD。我在此答案中发布了一个示例:
GCD,线程,程序流程和UI更新
You're posting the notification from the background thread.
From the NSNotificationCenter docs:
http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html
In your notification handling code you're updating ui which you must do from the main thread. Try moving that code to another method and then in the notification handling code, call it with performSelectorOnMainThread.
Another option is GCD without notifications. I posted a sample in this S.O. answer:
GCD, Threads, Program Flow and UI Updating