当应用程序从XCode运行但不作为独立应用程序运行时,文件拖放视图有效

时间:2014-02-14 15:55:13

标签: macos cocoa drag-and-drop

我制作了一个带有自定义视图的Mac应用程序,该视图是用于拖放文件的目标。我的视图已注册为目的地,我已实现了拖动操作方法。当我从XCode构建并运行应用程序时,一切正常,但是当我从Finder打开.app时,拖动文件不起作用,我在控制台中看到以下错误:

  

因为异常'NSInvalidArgumentException'而取消拖动   (推理路径无法访问的原因)是在拖动过程中引发的   会话

任何人都知道它的意义或原因是什么?以下是相关代码:

#import "DragDestinationView.h"

@implementation DragDestinationView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // register for dragging types
      [self registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, nil]];
      highlight = NO;
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

  if ( highlight ) {
    //highlight by overlaying a gray border
    [[NSColor whiteColor] setFill];
    NSRectFill(dirtyRect);
    [self setWantsLayer:YES];
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = 10.0f;
    [self.layer setBorderColor:[[NSColor grayColor] CGColor]];
  }
  else {
    [self.layer setBorderColor:[[NSColor clearColor] CGColor]];
  }
}

#pragma mark - Destination Operations

- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender {
  NSPasteboard *pboard = [sender draggingPasteboard];

  if ([[pboard types] containsObject:NSFilenamesPboardType]) {

    // check if it's a bin
    NSString* filePath = [[NSURL URLFromPasteboard: [sender draggingPasteboard]] absoluteString];
    if ([[[filePath substringFromIndex:[filePath length] - 4] lowercaseString] isEqualToString:@".bin"]) {
      // it's a bin
      highlight = YES;
      [self setNeedsDisplay:YES];

      return NSDragOperationCopy;
    }
  }
  return NSDragOperationNone;
}

- (void)draggingExited:(id <NSDraggingInfo>)sender
{
  //remove highlight of the drop zone
  highlight=NO;

  [self setNeedsDisplay: YES];
}

- (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender
{
  //finished with the drag so remove any highlighting
  highlight=NO;

  [self setNeedsDisplay: YES];

  return YES;
}

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
{
  if ( [sender draggingSource] != self ) {
    NSString* filePath = [[NSURL URLFromPasteboard: [sender draggingPasteboard]] absoluteString];
    filePath = [filePath substringFromIndex:7];
    filePath = [filePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"file path = %@",filePath);

    // send notification
    [[NSNotificationCenter defaultCenter] postNotificationName:@"filePathString" object:filePath];
  }
  return YES;
}


@end

注意:draggingEntered:方法返回NSDragOperationCopy,因为我喜欢带有绿色圆圈和加号的箭头光标,告诉用户他们可以在这里拖动文件。我实际上对删除的文件所做的就是抓住它的路径位置。

1 个答案:

答案 0 :(得分:2)

原来这不是拖放操作的问题,而是与设置NSTask的启动路径有关。如果要在/ usr / bin目录中执行二进制文件,则here的“启动路径无法访问”错误的解决方案位于here,如果要在应用程序的Resources文件夹中执行二进制文件,则{{3}}