2009-06-04 3 views
2

Da NSAppleScript Objekte werden immer auf der Haupt-Thread ausgeführt werden soll, habe ich ein kleines „Proxy“ Objekt zu verwenden:Warum ist NSAppleScript compileAndReturnError immer erfolgreich?

@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 

Dann ein Applescript zu kompilieren und ausführen:

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]; 

Wenn ich ein gültiges Skript kompiliere, funktioniert es wie erwartet; aber wenn ich ein Kauderwelsch Skript kompilieren, zum Beispiel „foo“, ist compileAndReturnError nicht scheitern, das heißt, gibt es YES und m_errorDict ist noch nil.

Warum?

Antwort

1

Versuchen Sie es im Skript-Editor. "Foo" kompiliert einfach gut; es läuft einfach nicht.

Try „*“ als Kompilierung Testskript.

BTW, ein Skript ausgeführt wird, kann einen Fehler auslösen, auch (wie Sie in Skript-Editor sehen). Stellen Sie sicher, dass Sie damit umgehen.