最近对 macOS 打开方式感兴趣。以下是最小验证模型。
PoC
- Info.plist
<dict>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeExtensions</key>
<array>
<string>jar</string>
</array>
<key>CFBundleTypeName</key>
<string>Java JAR file</string>
<key>CFBundleTypeRole</key>
<string>Viewer</string>
<key>LSHandlerRank</key>
<string>Default</string>
</dict>
</array>
</dict>
INFOPLIST_KEY_LSUIElement = YES
INFOPLIST_KEY_NSPrincipalClass = NSApplication
- XIB
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="23727" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="23727"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="jth-LA-gLs"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="AppDelegate"/>
</objects>
</document>
- main.m
#import <Cocoa/Cocoa.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
}
return NSApplicationMain(argc, argv);
}
- AppDelegate
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
@end
#import "AppDelegate.h"
@interface AppDelegate ()
@end
@implementation AppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
}
- (void)applicationWillTerminate:(NSNotification *)aNotification {
// Insert code here to tear down your application
}
- (BOOL)applicationSupportsSecureRestorableState:(NSApplication *)app {
return YES;
}
- (BOOL)application:(NSApplication *)sender openFile:(NSString *)filename {
NSLog(@"[DEBUG] openFile: called with file: %@", filename);
return YES;
}
- (void)application:(NSApplication *)sender openFiles:(NSArray<NSString *> *)filenames {
NSLog(@"[DEBUG] openFiles: called with files: %@", filenames);
}
/// If your delegate implements this method,
/// AppKit does not call the application:openFile: or application:openFiles: methods.
//- (void)application:(NSApplication *)application openURLs:(NSArray<NSURL *> *)urls {
// NSLog(@"[DEBUG] openURLs: called with URLs: %@", urls);
//}
@end
without XIB
- main.m
#import "AppDelegate.h"
#import <Cocoa/Cocoa.h>
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSApplication *app = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[app setDelegate:appDelegate];
[app run];
}
return 0;
}