【发布时间】:2010-12-30 05:52:06
【问题描述】:
更新 |我已经使用面板上传了一个示例项目并在此处崩溃:http://w3style.co.uk/~d11wtq/BlocksCrash.tar.gz(我知道“选择...”按钮没有任何作用,我还没有实现它)。
更新 2 |刚刚发现我什至不需要在 newFilePanel 上调用任何东西就可以导致崩溃,我只需要在语句中使用它。
这也会导致崩溃:
[newFilePanel beginSheetModalForWindow:[windowController window] completionHandler:^(NSInteger result) {
newFilePanel; // Do nothing, just use the variable in an expression
}];
似乎最后转储到控制台的内容有时是:“无法反汇编 dyld_stub_objc_msgSend_stret。”,有时是:“无法访问地址 0xa 的内存”。
我创建了自己的工作表(一个 NSPanel 子类),它尝试提供类似于 NSOpenPanel/NSSavePanel 的 API,因为它将自身呈现为工作表并在完成时调用一个块。
界面如下:
//
// EDNewFilePanel.h
// MojiBaker
//
// Created by Chris Corbyn on 29/12/10.
// Copyright 2010 Chris Corbyn. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@class EDNewFilePanel;
@interface EDNewFilePanel : NSPanel <NSTextFieldDelegate> {
BOOL allowsRelativePaths;
NSTextField *filenameInput;
NSButton *relativePathSwitch;
NSTextField *localPathLabel;
NSTextField *localPathInput;
NSButton *chooseButton;
NSButton *createButton;
NSButton *cancelButton;
}
@property (nonatomic) BOOL allowsRelativePaths;
+(EDNewFilePanel *)newFilePanel;
-(void)beginSheetModalForWindow:(NSWindow *)aWindow completionHandler:(void (^)(NSInteger result))handler;
-(void)setFileName:(NSString *)fileName;
-(NSString *)fileName;
-(void)setLocalPath:(NSString *)localPath;
-(NSString *)localPath;
-(BOOL)isRelative;
@end
以及实现里面的关键方法:
-(void)beginSheetModalForWindow:(NSWindow *)aWindow completionHandler:(void (^)(NSInteger result))handler {
[NSApp beginSheet:self
modalForWindow:aWindow
modalDelegate:self
didEndSelector:@selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo:(void *)[handler retain]];
}
-(void)dismissSheet:(id)sender {
[NSApp endSheet:self returnCode:([sender tag] == 1) ? NSOKButton : NSCancelButton];
}
-(void)sheetDidEnd:(NSWindow *)aSheet returnCode:(NSInteger)result contextInfo:(void *)contextInfo {
((void (^)(NSUInteger result))contextInfo)(result);
[self orderOut:self];
[(void (^)(NSUInteger result))contextInfo release];
}
如果我的块只是一个空主体的空操作,这一切都有效。关闭工作表时调用我的块。
EDNewFilePanel *newFilePanel = [EDNewFilePanel newFilePanel];
[newFilePanel setAllowsRelativePaths:[self hasSelectedItems]];
[newFilePanel setLocalPath:@"~/"];
[newFilePanel beginSheetModalForWindow:[windowController window] completionHandler:^(NSInteger result) {
NSLog(@"I got invoked!");
}];
但是,当我尝试从块内部访问面板时,我会因 EXC_BAD_ACCESS 而崩溃。例如,这会崩溃:
EDNewFilePanel *newFilePanel = [EDNewFilePanel newFilePanel];
[newFilePanel setAllowsRelativePaths:[self hasSelectedItems]];
[newFilePanel setLocalPath:@"~/"];
[newFilePanel beginSheetModalForWindow:[windowController window] completionHandler:^(NSInteger result) {
NSLog(@"I got invoked and the panel is %@!", newFilePanel);
}];
从调试器中不清楚原因是什么。堆栈上的第一项(零 0)只是说“??”并且没有列出任何内容。
堆栈中的下一项(1 和 2)分别是对 -endSheet:returnCode: 和 -dismissSheet: 的调用。查看调试器中的变量,似乎没有任何问题/超出范围。
我原以为面板可能已被释放(因为它是自动释放的),但即使在创建后立即调用 -retain 也无济于事。
我是不是执行错了?
【问题讨论】:
标签: objective-c macos cocoa objective-c-blocks nspanel