将委托设置为我班的实例?
问题描述:
我有一个C++/obj c文件集来为Growl(这是Obj C)创建一种C++包装,但是我被困在一个部分。我需要在我的Obj C类中设置一个Growl Delegate,以便注册被调用。将委托设置为我班的实例?
这是我.mm
#import "growlwrapper.h"
@implementation GrowlWrapper
- (NSDictionary *) registrationDictionaryForGrowl {
return [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObject:@"Upload"], GROWL_NOTIFICATIONS_ALL,
[NSArray arrayWithObject:@"Upload"], GROWL_NOTIFICATIONS_DEFAULT
, nil];
}
@end
void showGrowlMessage(std::string title, std::string desc) {
std::cout << "[Growl] showGrowlMessage() called." << std::endl;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[GrowlApplicationBridge setGrowlDelegate: @""];
[GrowlApplicationBridge
notifyWithTitle: [NSString stringWithUTF8String:title.c_str()]
description: [NSString stringWithUTF8String:desc.c_str()]
notificationName: @"Upload"
iconData: nil
priority: 0
isSticky: YES
clickContext: nil
];
[pool drain];
}
int main() {
showGrowlMessage("Hello World!", "This is a test of the growl system");
return 0;
}
和我的.h
#ifndef growlwrapper_h
#define growlwrapper_h
#include <string>
#include <iostream>
#include <Cocoa/Cocoa.h>
#include <Growl/Growl.h>
using namespace std;
void showGrowlMessage(std::string title, std::string desc);
int main();
#endif
@interface GrowlWrapper : NSObject <GrowlApplicationBridgeDelegate>
@end
现在你可以看到我的[GrowlApplicationBridge setGrowlDelegate: @""];
被设置为空字符串,我需要将其设置为这样的东西registrationDictionaryForGrowl
被调用,目前没有被调用。
但我不知道该怎么做。任何帮助?
答
您需要创建一个GrowlWrapper
的实例并将其作为代理传递给setGrowlDelegate:
方法。您只想在应用程序中这样做一次,因此每次拨打电话showGrowlMessage
都不太理想。您还需要保留对这个GrowlWrapper
的强烈参考,以便在完成之后释放它,或者在使用ARC时保持有效。所以,在概念上,你会想是在启动时执行以下操作:
growlWrapper = [[GrowlWrapper alloc] init];
[GrowlApplicationBridge setGrowlDelegate:growlWrapper];
而且在关机:
[GrowlApplicationBridge setGrowlDelegate:nil];
[growlWrapper release]; // If not using ARC
我得到一个错误'growlwrapper.mm:15:错误:“growlWrapper”在未声明这个范围(这一行是GrowlWrapper的分配线,我需要将growlWrapper添加到我的.h文件中吗?对不起,我是一个noob :( – Steven 2012-07-21 17:02:10
是的,你需要在某处声明growlWrapper。最简单的东西如果你只是想让你的测试工作就是在你分配/初始化之前插入'GrowlWrapper * growlWrapper'。 – 2012-07-21 17:10:29