Search code examples
cocoadrag-and-dropnsviewnsdragginginfo

Drag Drop delegate for NSView could not set an attribute


I am using NSView delegate to read the dragged excel values. For this I have subclassed NSView. My code is like-

@interface SSDragDropView : NSView
    {
        NSString *textToDisplay;
    }
    @property(nonatomic,retain) NSString *textToDisplay; // setters/getters

    @synthesize textToDisplay;// setters/getters

    @implementation SSDragDropView
    - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender{
        [self setNeedsDisplay: YES];
        return NSDragOperationGeneric;
    }

    - (void)draggingExited:(id <NSDraggingInfo>)sender{
        [self setNeedsDisplay: YES];
    }

    - (BOOL)prepareForDragOperation:(id <NSDraggingInfo>)sender {
        [self setNeedsDisplay: YES];
        return YES;
    }


   - (BOOL)performDragOperation:(id < NSDraggingInfo >)sender {
        NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
        if ([[[draggedFilenames objectAtIndex:0] pathExtension] isEqual:@"xls"]){
            return YES;
        } else {
            return NO;
        }
    }

    - (void)concludeDragOperation:(id <NSDraggingInfo>)sender{
        NSArray *draggedFilenames = [[sender draggingPasteboard] propertyListForType:NSFilenamesPboardType];
        NSURL *url =   [NSURL fileURLWithPath:[draggedFilenames objectAtIndex:0]];
       NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil]; //This text is the original excel text and its getting displayed.
    [self setTextToDisplay:textDataFile];
       }

I am setting the textDataFile value to a string attribute of that class. Now I am using SSDragDropView attribute value in some other class like-

SSDragDropView *dragView = [SSDragDropView new];
    NSLog(@"DragView Value is %@",[dragView textToDisplay]); 

But I am getting null each time. Is it like I can not set an attribute value in those delegate methods?


Solution

  • The above problem can be resolved just by declaring a global variable in your SSDragDropView.h class.

    #import <Cocoa/Cocoa.h>
    NSString *myTextToDisplay;
    @interface SSDragDropView : NSView
    {
    

    The same can be set inside the desired delegate method

    - (void)concludeDragOperation:(id <NSDraggingInfo>)sender {
    
    // .... //Your Code
    NSString *textDataFile = [NSString stringWithContentsOfURL:url usedEncoding:nil error:nil];
    myTextToDisplay = textDataFile;
    // .... //Your Code
    }
    

    :)