【发布时间】:2016-09-18 13:45:55
【问题描述】:
我正在编写由 Objective-C 实现的简单跨平台 C++ 层 (dylib)。通过平台宏包含特定于平台的部分。
NSUserNotificationCenter 需要委托模式来处理特定操作,例如单击通知。我面临的问题是,只要我执行send,就会发送通知,但之后实例会立即卸载。因此,onclick 通知操作永远不会被调用 (didActivateNotification),而是因为指针错误而崩溃。我怎样才能做到这一点?
注意:
SomeObjectiveC.mm 是位于我的应用程序中的一个类。 AppleUserNotificationManager.m 由 NotificationManager+apple.mm 初始化,两者都位于我的 Dylib 中。
SomeObjectiveC.mm
Notification *notification = new Notification;
notification->setTitle("Foo bar notification");
notification->setMessage("Hello world!");
NotificationManager *notificationManager = new NotificationManager;
notificationManager->send(notification);
NotificationManager+apple.mm
#include "notificationManager+apple.hpp"
bool NotificationManager::send(Notification *notification)
{
AppleUserNotificationManager *notificationManager = [[AppleUserNotificationManager alloc] init];
NSString *title = [NSString stringWithUTF8String:notification->getTitle().c_str()];
NSString *message = [NSString stringWithUTF8String:notification->getMessage().c_str()];
if (notification->getSoundName().empty()) {
[notificationManager sendWithTitle:title andMessage:message];
}
NSString *soundName = [NSString stringWithUTF8String:notification->getSoundName().c_str()];
[notificationManager sendWithTitle:title andMessage:message andSound: soundName];
return true;
}
AppleUserNotificationManager.m
#import "AppleUserNotificationManager.h"
@implementation AppleUserNotificationManager
@synthesize userNotification;
- (id)init
{
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate: self];
userNotification = [[NSUserNotification alloc] init];
self = [super init];
return self;
}
/**
* @param NSUserNotificationCenter center
* @param NSUserNotification notification
*
* @return bool
*/
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
/**
* @param NSUserNotificationCenter center
* @param NSUserNotification notification
*/
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
NSString *notificationText = [notification informativeText];
NSString *urlRegEx = @"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx];
if ([urlTest evaluateWithObject:notificationText]) {
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:notificationText]];
}
}
/**
* @param NSString title
* @param NSString message
* @param NSString soundName
*/
- (void)sendWithTitle:(NSString *)title andMessage:(NSString *)message andSound:(NSString *)soundName{
userNotification.title = title;
userNotification.informativeText = message;
userNotification.soundName = soundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification: userNotification];
}
@end
【问题讨论】:
标签: c++ objective-c delegates dynamic-linking