[英]In a Cocoa Application for macOS, I save a bundle to disk using NSFileWrapper. How can I get the finder show the correct icon for my bundle?
[英]macOS / Cocoa: How to get the path of the running app's main bundle after the user moves it on disk?
在macOS應用中,如果您需要獲取應用路徑或捆綁中的任何資源,則當然可以使用NSBundle
的mainBundle
靜態方法:
NSBundle *bundle = [NSBundle mainBundle];
NSString *appPath = [bundle bundlePath];
NSString *resourceFolderPath = [bundle resourcePath];
... etc ...
但是,如果在應用程序運行時用戶將應用程序的捆綁包移動到磁盤上的其他位置,則此方法將不起作用。 以上所有功能仍將返回用戶移動包之前的包的舊路徑。
無論用戶是否將其移動到磁盤上,如何獲取捆綁包的當前路徑或其中的任何資源的路徑?
到目前為止,我已經嘗試使用NSRunningApplication
來獲取其當前位置,如下所示:
NSRunningApplication *thisApp = [NSRunningApplication runningApplicationWithProcessIdentifier:getpid()];
NSLog(@"bundle URL: %@", [thisApp bundleURL]);
...但這也返回了捆綁包的舊路徑!
通常不支持移動已經運行的應用程序。 如果您確實需要支持這種情況,則可以執行以下操作:
首次啟動應用程序時,請像通常一樣獲取應用程序的當前路徑,然后為該路徑創建一個NSURL書簽。
每當您需要了解應用程序的當前路徑時,都可以解析在啟動時創建的NSURL書簽。 書簽將解析為應用程序的當前路徑,即使該應用程序已移動。
有關NSURL書簽的更多信息,請參見: https : //developer.apple.com/library/archive/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.