为什么NSAppleScript的compileAndReturnError总是成功?

时间:2009-06-04 02:54:10

标签: cocoa applescript

鉴于NSAppleScript对象总是应该在主线程上运行,我创建了一个小的“代理”对象来使用:

@interface AppleScriptProxy : NSObject {
    NSAppleScript *m_script;
    NSDictionary *m_errorDict;
}

- (id) init;

- (void) compileScript:
    (NSString*)script;

- (void) dealloc;

- (NSDictionary*) errorDict;

- (BOOL) failed;

- (void) runScript:
    (id)notUsed;

@end

@implementation AppleScriptProxy

- (id) init
{
    self = [super init];
    m_errorDict = nil;
    m_script = nil;
    return self;
}

- (void) dealloc
{
    //[m_errorDict release];
    [m_script release];
    [super dealloc];
}

- (void) compileScript:
    (NSString*)source
{
    m_script = [[NSAppleScript alloc] initWithSource:source];
    if ( m_script )
        if ( [m_script compileAndReturnError:&m_errorDict] ) {
            cerr << "compiled" << endl;
            [m_script retain];
        } else {
            cerr << "not compiled" << endl;
            m_script = nil;
        }
}

- (NSDictionary*) errorDict
{
    return m_errorDict;
}

- (BOOL) failed
{
    return !m_script || m_errorDict;
}

- (void) runScript:
    (id)notUsed
{
    [m_script executeAndReturnError:nil];
}

@end

然后,编译并执行AppleScript:

NSString *const script = /* some script */;

[proxy
    performSelectorOnMainThread:@selector(compileScript:)
    withObject:script waitUntilDone:YES];

if ( [proxy failed] ) {
    NSDictionary *errorDict = [proxy errorDict];
    NSString const *const errorMsg = errorDict ?
        [errorDict objectForKey:NSAppleScriptErrorMessage] :
        @"NSAppleScript initWithSource failed";
    cerr << [errorMsg UTF8String] << endl;
    return 1;
}

[proxy retain];
[proxy
    performSelectorOnMainThread:@selector(runScript:)
    withObject:nil waitUntilDone:NO];
[proxy autorelease];

如果我编译一个有效的脚本,它按预期工作;但是,如果我编译一个乱码脚本,例如“foo”,compileAndReturnError不会失败,即它返回YESm_errorDict仍然是nil

为什么?

1 个答案:

答案 0 :(得分:1)

在脚本编辑器中尝试。 “foo”编译得很好;它只是没有运行。

尝试使用“*”作为编译测试脚本。

BTW,运行脚本也会引发错误(正如您在脚本编辑器中看到的那样)。确保你处理它。