我被卡住了!
我正在尝试创建自定义模式对话框.我希望它使用块作为完成处理程序与NSSavePanel类似地执行.
我只复制了我认为需要的重要片段.
@implementation ModalWindowController
- (void)makeKeyAndOrderFront:(id)sender
modalToWindow:(NSWindow*)window
sourceRect:(NSRect)rect
completionHandler:(void (^)(NSInteger result))handler {
_handler = [handler retain];
session = [NSApp beginModalSessionForWindow:[self window]];
[[NSApplication sharedApplication] runModalSession:session];
[[self window] makeKeyAndOrderFrontCentered:self expandingFromFrame:rect];
}
- (IBAction)okButtonPressed:(id)sender {
[[self window] orderOut:self];
_handler(NSOKButton);
[NSApp endModalSession:session];
}
@end
Run Code Online (Sandbox Code Playgroud)
现在我可以使用代码调用它:
[self.modalWindowController makeKeyAndOrderFront:self
modalToWindow:[[self view] window]
sourceRect:sr
completionHandler:^(NSInteger result) {
NSLog(@"Inside Block");
if ( result == NSOKButton ) {
// do something interesting here
}
}];
NSLog(@"Errg");
Run Code Online (Sandbox Code Playgroud)
但是,在方法makeKeyAndOrderFront之后一切顺利:modalToWindow:sourceRect:completionHandler:已经完成它不会阻塞线程,因此即使用户没有选择"ok"或"cancel",也会打印"Errg".此时显示模态窗口,用户单击"确定",然后执行_handler块.但是,如果我尝试访问块中的局部变量,并且应用程序崩溃,因为所有内容已经清理干净.
从makeKeyAndOrderFront:...方法阻止主线程的最佳方法是什么?这是使用块实现完成处理程序的正确方法吗?
所以,我有点像perl newb.虽然我有一些更复杂的事情,但我突然遇到了障碍,无法弄清楚wtf是错误的代码.我已经大大简化了它,它只是一小段代码.
Test.pl
package Test;
sub new {
my ($class) = shift;
my $self = {
_attr => "asdfa"
};
bless $self, $class;
return $self;
}
sub log {
print "\nAccessed via class: ".$self->{_attr};
}
Run Code Online (Sandbox Code Playgroud)
process.pl
#!/usr/bin/perl
do "Test.pl";
use strict;
use warnings;
use diagnostics;
my($test) = new Test();
$test->log;
print "\nAccessed via main: ".$test->{_attr};
Run Code Online (Sandbox Code Playgroud)
我运行process.pl,得到以下输出
通过课程
访问:通过main访问:asdfa
我也得到了警告
在连接(.)中使用未初始化的值或在Test.pl第12行(#1)使用字符串(W未初始化)使用未定义的值,就像它已经定义一样.它被解释为""或0,但也许这是一个错误.要禁止此警告,请为变量分配定义的值.
所以问题是$ self实际上是未定义的.为什么,我不知道.这不是初始化对象的方法吗?