Cocoa: Call App Delegate Method from another Class

2019-05-23 23:22发布

问题:

I'm currently trying to get the path of a file from a drag and drop operation inside of a custom view, and then pass that path to my app delegate. I'm currently using the following:

- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender 
{

    NSPasteboard *pb = [sender draggingPasteboard];
    NSString *type = [pb availableTypeFromArray:[NSArray arrayWithObject:NSFilenamesPboardType]];
    NSArray *array = [[pb stringForType:type] propertyList];

    //access the app delegate
    NSApplication *myApplication;
    myApplication = [NSApplication sharedApplication];

    [myApplication uploadFiles:array];

    return NO;

} 

However, I keep getting a message that says that my app delegate doesn't respond to the "uploadFiles" method. It is declared inside of my app delegate. Am I accessing the NSApplication in the correct manner?

Thanks.

回答1:

I believe the problem is that you're referring to the application but not its delegate. This should work:

Mac

[(YourAppDelegate *)[[NSApplication sharedApplication] delegate] uploadFiles:array]

replacing YourAppDelegate with your actual app delegate name, and being certain to #import it.