2011-03-16 23 views
7

目前有我的應用程序inteface一個按鈕,允許打開一個文件,這裏是我的開放代碼:可可/對象 - - 打開文件拖放到應用程序圖標時

在我app.h:

- (IBAction)selectFile:(id)sender; 

在我app.m:

@synthesize window; 

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 

} 

- (IBAction)selectFile:(id)sender { 

    NSOpenPanel *openPanel = [NSOpenPanel openPanel]; 
    NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil]; 

    NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ]; 

    if(result == NSOKButton){ 

     NSString * input = [openPanel filename]; 

如何編輯我的代碼,以便與應用程序圖標拖動&滴口?
注意:我編輯了.plist文件並添加了一行「xml」,但它改變了任何內容,當我的文件被放在圖標上時發生錯誤。
注2:我鏈接的「文件 - >打開...」以選擇文件:至極參考我的代碼
注3:我的應用程序不是基於文檔的應用程序


感謝您的幫助!
Miskia

+0

爲什麼不使用NSDocument?不夠靈活? – 2011-03-16 21:18:26

回答

15

首先在.plist文件中添加適當的CFBundleDocumentTypes擴展名。

下實現以下代表:
- 應用:中openFile:(一個文件刪除)
- 應用:openFiles散:(多個文件刪除)

參考:
NSApplicationDelegate Protocol Reference

迴應評論:

分步考試PLE,希望它讓一切清晰:)

添加到文件的.plist:

<key>CFBundleDocumentTypes</key> 
     <array> 
      <dict> 
       <key>CFBundleTypeExtensions</key> 
       <array> 
        <string>xml</string> 
       </array> 
       <key>CFBundleTypeIconFile</key> 
       <string>application.icns</string> 
       <key>CFBundleTypeMIMETypes</key> 
       <array> 
        <string>text/xml</string> 
       </array> 
       <key>CFBundleTypeName</key> 
       <string>XML File</string> 
       <key>CFBundleTypeRole</key> 
       <string>Viewer</string> 
       <key>LSIsAppleDefaultForType</key> 
       <true/> 
      </dict> 
     </array> 

添加到... AppDelegate.h

- (BOOL)processFile:(NSString *)file; 
- (IBAction)openFileManually:(id)sender; 

加入... AppDelegate.m

- (IBAction)openFileManually:(id)sender; 
{ 
    NSOpenPanel *openPanel = [NSOpenPanel openPanel]; 
    NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil]; 
    NSInteger result = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ]; 
    if(result == NSOKButton){ 
     [self processFile:[openPanel filename]]; 
    } 
} 

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename 
{ 
    return [self processFile:filename]; 
} 

- (BOOL)processFile:(NSString *)file 
{ 
    NSLog(@"The following file has been dropped or selected: %@",file); 
    // Process file here 
    return YES; // Return YES when file processed succesfull, else return NO. 
} 
+0

我爲CFBundleDocumentTypes(* .xml文件)添加了適當的擴展但我不明白如何配置委託...當時我有一個「selectFile」和所有我的代碼取決於我的selectFile的結果。 ..我如何工作和使用selectFile和openFile(允許拖放功能)進行配置...感謝您的幫助! – Nono 2011-03-16 22:10:07

+0

我添加了一些額外的信息,這解釋瞭如何用一段代碼處理丟棄和選定的文件。 – Anne 2011-03-16 23:16:20

+0

工作很棒!非常感謝安妮! – Nono 2011-03-16 23:46:00

相關問題