从子类调用AppDelegate方法?

时间:2014-05-12 01:55:31

标签: objective-c cocoa

我可能不会在逻辑上解释这个,因为我是Objective-C的新手,但是我在这里......

我在Objective-C中编写了一个与WebView交互的应用程序。该应用程序的一部分涉及通过NSSharingService中当前显示的WebView共享图像。因此,我在AppDelegate.m文件中定义了这样的方法:

#import "CCAppDelegate.h"
#import <WebKit/WebKit.h>
#import <AppKit/AppKit.h>

@implementation CCAppDelegate

    -(void)shareFromMenu:(id)sender shareType:(NSString *)type{
        NSString *string = [NSString stringWithFormat: @"window.function('%@')", type];
        [self.webView stringByEvaluatingJavaScriptFromString: string];
    }

@end

然后我在NSMenu中定义了一个CCShareMenu.m的子类,它创建了一个可用的共享选项菜单:

#import "CCShareMenu.h"

@implementation CCShareMenu

- (void)awakeFromNib{
    [self setDelegate:self];
}

- (IBAction)shareFromService:(id)sender {
    NSLog(@"%@", [sender title]);
    // [CCAppDelegate shareFromMenu]; 
}

- (void)menuWillOpen:(NSMenu *)menu{
    [self removeAllItems];
    NSArray *shareServicesForItems = @[
        [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeMessage],
        [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeEmail],
        [NSSharingService sharingServiceNamed:NSSharingServiceNamePostOnFacebook],
        [NSSharingService sharingServiceNamed:NSSharingServiceNamePostOnTwitter]
    ];
    for (NSSharingService *service in shareServicesForItems) {
        NSMenuItem *item = [[NSMenuItem alloc] init];
        [item setRepresentedObject:service];
        [item setImage:[service image]];
        [item setTitle:[service title]];
        [item setTarget:self];
        [item setAction:@selector(shareFromService:)];
        [self addItem:item];
    }
}

@end

这些方法都可以自行运行,但我需要在shareFromMenu shareFromService内调用IBAction方法。

我尝试将IBAction方法移动到AppDelegate.m,然后意识到这没有意义,因为menuWillOpen - 创建的选择器永远找不到正确的方法。同样,我尝试按照here发布的说明进行操作,但是:

[CCAppDelegate shareFromMenu];

还回复了一条错误消息,指出找不到该方法。

我意识到我在这里做了一些根本错误的事情,因此我们将非常感谢指导。

2 个答案:

答案 0 :(得分:1)

-[CCAppDelegate shareFromMenu]

不同

-[CCAppDelegate shareFromMenu:shareType:]

我会尝试在@interface@end之间向CCAppDelegate.h添加以下内容:

-(void)shareFromMenu:(id)sender shareType:(NSString *)type

然后将您的shareFromService:方法更改为:

- (IBAction)shareFromService:(id)sender
{
    NSString *shareType = @"Set your share type string here.";

    CCAppDelegate *appDelegate = (CCAppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate shareFromMenu:sender shareType:shareType];
}

答案 1 :(得分:1)

- (void)shareFromMenu是一个成员方法,但是

[CCAppDelegate shareFromMenu]

正在调用一个类函数,这不是调用成员函数的正确方法。

您可以尝试获取CCAppDelegate实例,然后像这样调用函数

CCAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; [appDelegate shareFromMenu];

相关问题