我GRA從我的MDFoundationAdditions
和MDAppKitAdditions
類別中剔除這些。
這個解決方案應該爲Mac OS X 10.4.X及更高的工作(這是LSOpenApplication()被引入時):
MDAppKitAdditions.h:
#import <Cocoa/Cocoa.h>
#import "MDFoundationAdditions.h"
@interface NSWorkspace (MDAdditions)
- (BOOL)launchApplicationAtPath:(NSString *)path
arguments:(NSArray *)argv
error:(NSError **)error;
@end
MDAppKitAdditions.m:
#import "MDAppKitAdditions.h"
#if MAC_OS_X_VERSION_MIN_REQUIRED <= MAC_OS_X_VERSION_10_4
#include <ApplicationServices/ApplicationServices.h>
#elif MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
#include <CoreServices/CoreServices.h>
#endif
@implementation NSWorkspace (MDAdditions)
- (BOOL)launchApplicationAtPath:(NSString *)path arguments:(NSArray *)argv
error:(NSError **)error {
BOOL success = YES;
if (error) *error = nil;
if (path) {
FSRef itemRef;
if ([path getFSRef:&itemRef error:error]) {
LSApplicationParameters appParameters =
{0, kLSLaunchDefaults, &itemRef, NULL, NULL,
(argv ? (CFArrayRef)argv : NULL), NULL };
OSStatus status = noErr;
status = LSOpenApplication(&appParameters, NULL);
if (status != noErr) {
success = NO;
NSLog(@"[%@ %@] LSOpenApplication() returned %hi for %@",
NSStringFromClass([self class]),
NSStringFromSelector(_cmd), status, path);
if (error) *error =
[NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
}
}
}
return success;
}
@end
MDFoundationAdditions.h:
#import <Foundation/Foundation.h>
#import <CoreServices/CoreServices.h>
@interface NSString (MDAdditions)
- (BOOL)getFSRef:(FSRef *)anFSRef error:(NSError **)anError;
@end
個
MDFoundationAdditions.h:
#import "MDFoundationAdditions.h"
#import <sys/syslimits.h>
@implementation NSString (MDAdditions)
- (BOOL)getFSRef:(FSRef *)anFSRef error:(NSError **)anError {
if (anError) *anError = nil;
OSStatus status = noErr;
status = FSPathMakeRef((const UInt8 *)[self UTF8String], anFSRef, NULL);
if (status != noErr) {
if (anError)
*anError = [NSError errorWithDomain:NSOSStatusErrorDomain code:status userInfo:nil];
}
return (status == noErr);
}
@end
有使用NSWorkspace一個問題,我想傳遞一個文件名作爲NSWorkspace函數的參數,如果應用程序已經運行意味着新的實例不會創建參數部分會被忽略這使得它在這種情況下無法使用 – user549164 2011-02-08 01:47:20
那麼在這種情況下,可能使用NSTask啓動應用程序,然後立即使用其中一種NSWorkspace啓動方法,因爲NSWorkspace方法會在應用程序已經運行的情況下將它們帶到前端。 – indragie 2011-02-08 03:30:25
@ user549164:您可以提供`NSWorkspaceLaunchNewInstance`來始終啓動一個新實例(如果適用的話)。 – 2013-05-18 15:11:48