我正在嘗試爲在Mac上運行的應用使用Objective-C爲Unity創建一個插件。我需要從使用url協議的鏈接啓動我的應用時獲取URL。我之前沒有使用過Objective-C,所以我在嘗試使它工作時遇到了麻煩。在包中使用NSApplication委託
我正在使用Unity提供的示例(download example)並將方法更改爲我需要的URL,但我的應用在_GetUrl方法上的行nsApplication = [[NSApplication alloc] init];
上崩潰。我不知道我在想什麼/做錯了什麼。另外,_GetUrl是我想要求URL(在第一幀被調用)時從Unity調用的方法,但恐怕可能會在applicationWillFinishLaunching之後調用。那麼我應該在哪裏設置委託,以便在委派設置後發生applicationWillFinishLaunching?
我使用.h和.m腳本,然後編譯捆綁包並將其作爲插件導入Unity。這是我的代碼:
PluginUrlHandler.h
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
@interface NSApplicationDelegate : NSObject
{
NSString* urlString;
}
// NSApplication delegate methods
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification;
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent;
//Other methods
- (NSString *)getUrl;
@end
PluginUrlHandler.m
#import <Foundation/Foundation.h>
#import "PluginUrlHandler.h"
@implementation NSApplicationDelegate
- (id)init
{
self = [super init];
urlString = @"nourl";
return self;
}
- (void)applicationWillFinishLaunching:(NSNotification *)aNotification
{
NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager];
[appleEventManager setEventHandler:self
andSelector:@selector(handleGetURLEvent:withReplyEvent:)
forEventClass:kInternetEventClass andEventID:kAEGetURL];
}
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
[event paramDescriptorForKeyword:keyDirectObject] ;
NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
urlString = urlStr;
}
- (NSString *)getUrl
{
return urlString;
}
@end
static NSApplicationDelegate* delegateObject = nil;
static NSApplication* nsApplication = nil;
// Helper method to create C string copy
char* MakeStringCopy (const char* string)
{
if (string == NULL)
return NULL;
char* res = (char*)malloc(strlen(string) + 1);
strcpy(res, string);
return res;
}
#if c__plusplus
extern "C" {
#endif
const char* _GetUrl()
{
if (delegateObject == nil)
delegateObject = [[NSApplicationDelegate alloc] init];
if (nsApplication == nil)
nsApplication = [[NSApplication alloc] init];
[nsApplication setDelegate:delegateObject];
return MakeStringCopy([[delegateObject getUrl] UTF8String]);
}
#if c__plusplus
}
#endif
「我之前沒有使用Objective-C」!!!!!!!!你會發現它非常困難,至少需要3年的時間才能掌握Xcode/OSX版本的基本知識。 :O – Fattie
3年?!來吧!但是我發現OP沒有關於委託和應用程序實例的線索。我建議先寫一個OS X的應用程序,並採取一些教程,直到你瞭解基本架構 –
找到這個,這幫助我,實際上http://stackoverflow.com/a/2154666 –